从两个 data.table 中创建一个 data.table,名称为列 [2],不同

Make a data.table out of two data.table, with the name of column[2], different

当 运行 我显示代码时,我收到以下警报:

Column 2 ['t2'] of item 2 is missing in item 1. Use fill=TRUE to fill with NA (NULL for list columns), or use.names=FALSE to ignore column names. use.names='check' (default from v1.12.2) emits this message and proceeds as if use.names=FALSE for backwards compatibility. See news item 5 in v1.12.2 for options to control this message.

如何更正?

library(data.table)
DT = data.table(Smp=1:9,
                s=as.character(seq(as.POSIXct("2020-01-01"), by = "1 sec",length.out = 9)),
                x=rep(c("b","a","c"),each=3), y=c(1,3,6))
DT2=data.table(Smp=1:9,
               t2=as.character(seq(as.POSIXct("2020-01-02"), by = "1 sec",length.out = 9)),
               x=rep(c("h","j","a"),each=3), y=c(2,5,8))
#seq(as.POSIXct("2001-01-01 04:15:20 "), by = "1 sec",length.out = 9)

tmp_dir = tempdir()
setwd(tmp_dir)
getwd()
fwrite(DT, "file2020-1.csv")
fwrite(DT2,"file2020-2.csv")

#fread("file2020-1.csv")
#fread("file2020-2.csv")

files = list.files(pattern="*.csv")#path=tmp_dir
files
rDT = rbindlist(lapply(files[c(1,2)],fread,fill=TRUE,stringsAsFactors=FALSE,check.names = T))
#2
l <- lapply(files[c(1,2)], fread,fill=TRUE,stringsAsFactors=FALSE,check.names = T)
dt <- rbindlist( l )

data.table原本各有207列

警告是因为两个数据框中的列名不同,合并为一个时不匹配。

您可以在两个数据框中使用相同的名称,这样可以避免警告。

library(data.table)

cols <- c('Smp', 's','x', 'y')
rDT = rbindlist(lapply(files[c(1,2)], function(x) 
  setnames(fread(x, fill=TRUE,stringsAsFactors=FALSE,check.names = TRUE), cols)))