首页 > 解决方案 > 从包含使用 For 循环指定文件来源的列的多个文件创建数据框

问题描述

我有四个 CSV 文件。这些文件中的每一个在结构上都是相同的,包含 21 列(第一列是时间点),接下来的 20 列是不同类型的数据点。但是,每个文件都有不同的行数。

我希望为 20 列中的每一列(除第一列之外的所有列,即时间)创建一个数据框。此数据框将包含两列(1:来自所有四个 CSV 文件的特定列(即列号 3)的我的数据和 2:级别(1 用于从 CSV 文件 1 获取的数据点,2 用于 CSV 文件 2、3 CSV 文件 3 和 4 用于 CSV 文件 4)。

任何帮助是极大的赞赏!

谢谢你,J

因为我想完成这个任务 20 次,所以我认为使用 for 循环是明智的。下面是我的代码。每次运行代码时都会出现相同的错误:“要替换的项目数不是替换长度的倍数”。

# Vectors contains the vectors that will hold the data specific to each column from all four CSV files
# Doc1, Doc2, Doc3, and Doc4 are data frames that contain each of the columns (besides the first one (time)) of the original CSV files. In this case, the first column in any of these files corresponds to the second column in the original CSV file. 

Vectors = c(Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16, Col17, Col18, Col19, Col20, Col21)

for (value in c(1:20)) {
  Levels = c() # levels signifies the document of origin per data point (i.e. 1 for CSV file 1, 2 for CSV file 2, etc.)
  Vectors[value] = c(Doc1[,value])
  Vectors[value] = append(Vectors[value], Doc2[,value])
  Vectors[value] = append(Vectors[value], Doc3[,value])
  Vectors[value] = append(Vectors[value], Doc4[,value])
  Levels = c(rep(1, length(Doc1[,value]))
  Levels = append(Levels, rep(2, length(Doc2[,value])))
  Levels = append(Levels, rep(3, length(Doc3[,value])))
  Levels = append(Levels, rep(4, length(Doc4[,value])))
  Vectors[value] = data.frame(Vectors[value], Levels)
}

我希望 for 循环能够运行并将值分配给 Vectors 中的每个向量。同样,分配给这些向量的值将是存储在每个 CSV 文件(doc1、doc2、doc3、doc4)中特定数字列中的数据。然后我期望 for 循环生成与每个数据点对应的级别。然后,我希望 for 循环将这两个作为数据帧连接起来,这将被命名为 Col2、Col3 等,具体取决于 for 循环运行了多少次。

相反,我会收到以下警告消息:要替换的项目数不是替换长度的倍数。

再次,提前感谢任何和所有的帮助。我是 R 新手,我非常感谢任何人提供的任何建议。

标签: rloopsvectorappendorganization

解决方案


你可能会认为你已经问过这个问题了,一张图片(或数据!)值一千字。我可以建议您将您的问题归结为尽可能小的数据集,我什至可以建议为您的问题开发伪代码并显示它。


推荐阅读