【问题标题】:R - combining lines from multiple CSV into a data frameR - 将来自多个 CSV 的行组合成一个数据框
【发布时间】:2016-03-21 13:19:54
【问题描述】:

我有一个文件夹,其中包含数百个 CSV 文件,每个文件都包含特定邮政编码的数据。

每个 CSV 文件包含两列和数千行。描述符在 A 列,值在 B 列。

我需要从每个文件中提取两条信息,并使用 [Column A, Row 2](邮政编码)和 [Column B, Row 1585](即收入中位数)。

最终结果应该是一个包含两列的表格/数据框:一列用于邮政编码,另一列用于收入中位数。

任何帮助或建议将不胜感激。

【问题讨论】:

标签: r csv


【解决方案1】:

免责声明:这个问题非常模糊。下次,一定要添加一个可以在我们的机器上运行的可重现示例。它将帮助您、回答您问题的人以及未来的用户。

你可以试试这样的:

files = list.files("~/Directory")

my_df = data.frame(matrix(ncol = 2, nrow = length(files)

for(i in 1:length(files)){
    row1 = read.csv("~/Directory/files[i]",nrows = 1)
    row2 = read.csv("~/Directory/files[i]", skip = 1585, nrows = 1)
    my_df = rbind(my_df, rbind(row1, row2))
}

my_df = my_df[,c("A","B")]
# Note on interpreting indexing syntax: 
  Read this as "my_df is now (=) my_df such that ([) the columns (,) 
  are only A and B (c("A", "B")) "

【讨论】:

  • 你的意思可能是rbind(row1, row2)
  • @Frash 我的意思是两者(尽管这并不排除出现错误的可能性);我想将现有数据框(我正在构建的)与新行(也需要绑定在一起)绑定。
  • 问题是第 1 行只有一条信息,而第 1585 行有两条。您的代码和建议给了我很多工作机会,所以我应该一切顺利。
  • @Pubb 你需要在第 1 行的第 2 列放一些东西,即使它是一个 NA 值。
  • @Nancy:你能解释一下最后两个作业在做什么吗?谢谢
【解决方案2】:

您可以使用list.files 函数获取所有文件的目录,然后在for 循环中使用read.csvrbind 创建一个data.frame

类似这样的:

direct<-list.files("directory_to_your_files")
df<-NULL
for(i in length(direct)){
  df<-rbind(df,read.csv(direct[i]))
}

【讨论】:

    【解决方案3】:

    所以这是我想要它做的代码。如果有更优雅的解决方案,请随时指出。

    # set the working directory to where the data files are stored
    setwd("/foo")
    
    # count the files
    files = list.files("/foo")
    
    #create an empty dataframe and name the columns
    
    dataMatrix=data.frame(matrix(c(rep(NA,times=2*length(files))),nrow=length(files)))
    colnames(dataMatrix)=c("Postal Code", "Median Income")
    
    # create a for loop to get the information in R2/C1 and R1585/C2 of each data file
    # Data is R2/C1 is a string, but is interpreted as a number unless specifically declared a string
    
    for(i in 1:length(files)) {
      getData = read.csv(files[i],header=F)
      dataMatrix[i,1]=toString(getData[2,1])
      dataMatrix[i,2]=(getData[1585,2])
    }
    

    感谢所有帮助我解决这个问题的人,尤其是南希。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多