【问题标题】:How to add column 1 of second csv file under the column 1 of the first csv file using R如何使用 R 在第一个 csv 文件的第 1 列下添加第二个 csv 文件的第 1 列
【发布时间】:2015-06-21 21:05:54
【问题描述】:

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

示例 文件1.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

结果 结果.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)) 中的错误: 名字与以前的名字不匹配

【问题讨论】:

  • 试试,do.call(rbind,myfiles)

标签: r csv export-to-csv


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    数据框可以附加“行绑定”语法,如rbind(df1,df2,df3,...)

    如果你有数据框列表,可以使用do.call绑定:

    do.call(rbind,myfiles)
    

    【讨论】:

      【解决方案3】:
         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=",")
      

      【讨论】:

        猜你喜欢
        • 2021-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-20
        • 1970-01-01
        相关资源
        最近更新 更多