如何使用 R 在第一个 csv 文件的第 1 列下添加第二个 csv 文件的第 1 列

How to add column 1 of second csv file under the column 1 of the first csv file using R

我有多个 csv 文件。我想将所有 csv 文件中所有列的内容放在一列中。我也不希望其中包含特定行数。

例子 file1.csv

         Column1 Column2
            A       1  
            B       2
            C       3
            D       4
            E       5

file2.csv

         Column1 Column2
           F         6
           G         7
           H         8
           I         9
           J         10

结果 Result.csv

        Column1  Column2
          C          3
          D          4
          E          5
          H          8
          I          9
          J          10

我的代码:

   temp = list.files(pattern="*.csv")
   myfiles = lapply(temp, read.delim,nrow=4292,skip=1472,sep=",")
   nana<-do.call(rbind,myfiles)
   write.table(nana,"result_polmeans.csv",sep=",")

此代码为每个 csv 文件生成 2 列。错误源于 do.call 函数 match.names(clabs, names(xi)) 中的错误: 名称与以前的名称不匹配

创建myfiles后可以使用Reduce来解决这个问题

all.data <- Reduce(function(x,y) rbind(x, y), myfiles)

它将获取 myfiles 列表并将其所有元素绑定在一起,留下一个数据框传递给 write.table

数据帧可以附加 "row-bind" 语法,如 rbind(df1,df2,df3,...)

如果你有一个数据框列表,do.call可以用来绑定它们:

do.call(rbind,myfiles)
   temp = list.files(pattern="*.csv")
   new.data <- NULL

   for(i in temp) { 
                   in.data <- read.table(i,skip=1472,sep=",")
                   new.data <- rbind(new.data, in.data)
                }

   write.table(new.data,"result_polmeans.csv",sep=",")