使用R将多个文件合并到一个数据库中

使用R将多个文件合并到一个数据库中,r,merge,reshape2,melt,R,Merge,Reshape2,Melt,我一直在尝试导入几个csv文件,使用函数“melt”并将它们合并到R中的单个数据库中。所有文件都有一个“id”、“date.time”和“tag”列;但是,其余的列在不同的文件中有所不同。这是一个文件中几行的示例: date.time标签111015 111016 113949 113950 1 1 2012-10-11 00:00:00 14767 0 0 0 0 2 2 2012-10-11 01:00:00 14767 0 0

我一直在尝试导入几个csv文件,使用函数“melt”并将它们合并到R中的单个数据库中。所有文件都有一个“id”、“date.time”和“tag”列;但是,其余的列在不同的文件中有所不同。这是一个文件中几行的示例:

date.time标签111015 111016 113949 113950
1 1 2012-10-11 00:00:00 14767      0      0      0      0
2 2 2012-10-11 01:00:00 14767      0      0      0      0
3 3 2012-10-11 02:00:00 14767      0      0      0      0
4 4 2012-10-11 03:00:00 14767      0      0      0      0
5 5 2012-10-11 04:00:00 14767      0      0      0      0
6 6 2012-10-11 05:00:00 14767      0      0      0      0
图书馆(E2)
#导入文件

文件最好先使用
lappy
加载所有内容,然后使用
melt
如下:(假设所有文件都在变量
文件中

Note: Untested 
require(reshape2)
files <- list.files(my.dir, full.names = TRUE)
# first load all files
dd <- lapply(1:length(files), function(idx) {
    d <-read.csv(files[idx], header = TRUE, sep=",", check.names = FALSE)
    # if you want the file index
    d$file.idx <- idx
    d
})
# merge all
dd <- do.call(rbind, dd)
# now melt
dd.m <- melt(dd, c(4:length(d)), c("date.time","tag"), variable.name = "receiver")
注:未经测试
要求(2)

由于某些原因,在我尝试使用melt函数后,它会给我一个错误“error:measure variables not found in data:NA”。现在,我更喜欢先熔化文件,然后进行合并,因为每个文件都有不同的行号,尽管每个文件都有“id”、“date.time”和“tag”列,表示不同接收器编号的计数的其余列在2和6之间变化。但是,如果执行melt,则之后合并它们应该更容易。保持每个变量格式(例如,日期/时间格式、数字、间隔等)的最佳方法是什么当使用melt/rbind时?rbind的问题是它会更改每个变量的格式(“日期.时间”作为字符,“变量”作为字符,等等)。你能用merge代替do.call(rbind,dd.m)吗?
for(j in 1:length(data)){
   dm<-melt(data[[j]],measure.vars=c(4:length(data[[j]])),
     id=c("date.time","tag"),variable.name="receiver")

   results<-rbind(dm)   

  }
Note: Untested 
require(reshape2)
files <- list.files(my.dir, full.names = TRUE)
# first load all files
dd <- lapply(1:length(files), function(idx) {
    d <-read.csv(files[idx], header = TRUE, sep=",", check.names = FALSE)
    # if you want the file index
    d$file.idx <- idx
    d
})
# merge all
dd <- do.call(rbind, dd)
# now melt
dd.m <- melt(dd, c(4:length(d)), c("date.time","tag"), variable.name = "receiver")
Note: Untested 
require(reshape2)
files <- list.files(my.dir, full.names = TRUE)
dd.m <- lapply(1:length(files), function(idx) {
    # load the file
    d <-read.csv(files[idx], header = TRUE, sep=",", check.names = FALSE)
    # now melt immediately
    d.m <- melt(d, c("date.time","tag"), c(4:length(d)))
})
# merge all
dd.m <- do.call(rbind, dd.m)