【问题标题】:Writing multiple columns from different files into one data frame in R将不同文件中的多列写入R中的一个数据帧
【发布时间】:2021-08-24 09:03:38
【问题描述】:

我的文件夹中有以下文件 clust_rot_10_.csv,clust_rot_11_.csv,clust_rot_12_.csv,clust_rot_3_.csv,clust_rot_4_.csv,clust_rot_5_.csv,clust_rot_6_.csv,clust_rot_7_.csv,clust_rot_7_.csv,clust_rot_8_.csv,clust_rot_9_.csv,driver_rot_10_.csv, driver_rot_11_.csv,driver_rot_12_.csv,driver_rot_3_.csv,driver_rot_4_.csv,driver_rot_5_.csv,driver_rot_6_.csv,driver_rot_7_.csv,driver_rot_8_.csv,driver_rot_9_.csv

在以clust_rot_开头的文件中,有两列X和Y。我需要从所有以clust_rot_开头的文件中检索Y列的数据> 使用 R 程序。请帮忙解决这个问题

【问题讨论】:

  • “帮助”表示您已经开始任务并需要帮助。到目前为止,您尝试了什么,为什么没有成功?
  • 你能澄清一下a)你想以什么方式将文件合并到一个data.frame中(作为不同的列?都在相同的两列中?)b)合并的主键是什么两个文件到不同的列(行号?)。
  • 我希望它们在同一个文件中作为不同的列。所有文件中的行数都相同。没有主键,我只希望它们并排。我需要使用“for”循环自动执行此操作。

标签: r csv


【解决方案1】:

解决方法如下:

  1. 使用read.table 加载第一个文件并将其存储在data.frame x
  2. 在所有剩余文件的循环中,将每个文件读入临时 data.frame(例如 newdata)并将其附加到先前使用 cbind(x, newdata) 加载的数据中

内置数据集示例iris

x <- iris[,1:2]
newdata <- iris[,3:4]
x <- cbind(x, newdata)

【讨论】:

  • 首先,感谢您的快速回复。我理解你回答的第一部分。但是,我不清楚第二部分。如果可能的话,如果您能详细说明一下或分享代码,那就太好了。
  • 我添加了一个使用cbind的例子。
【解决方案2】:

试试这个代码 -

#Get vector of filenames that has 'clust_rot_' in it. 
filenames <- list.files(pattern = 'clust_rot_', full.names = TRUE)
#From each file read the file and extract Y column from  it.
result <- as.data.frame(lapply(filenames, function(x) read.csv(x)$Y))
#Rename the columns with the name of the file
names(result) <- tools::file_path_sans_ext(basename(filenames))
#Write it as new csv
write.csv(result, 'result.csv', row.names = FALSE)

【讨论】:

  • 非常感谢您的意见。但是,结果文件结果是空的。第二行代码没有读取任何内容。变量“结果”有 0 个观察值。
  • 1. filenames 是否具有您要读取的文件的所有正确名称?它包含什么? 2. 您的 csv 文件在哪里?它在您的工作目录中吗?检查getwd()。如果文件不在工作目录中,您需要在list.files 中提供 csv 文件的路径。 filenames &lt;- list.files(path = '/location/of/csv/files', pattern = 'clust_rot_', full.names = TRUE)
  • 对不起,罗纳克。我的坏变量名是错误的。不是Y,是x。非常感谢你的帮助。它奏效了。
猜你喜欢
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 2014-12-29
  • 2022-01-08
  • 2020-08-25
  • 1970-01-01
  • 2021-05-15
相关资源
最近更新 更多