[英]Writing multiple columns from different files into one data frame in R
I have the following files in the folder 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_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_.Z628CB5675FF524F3E I have the following files in the folder 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_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_.Z628CB5675FF524F3E 719B7AA2E88FE3FZ 719B7AA2E88FE3FZ
In the files that start with clust_rot_ , there are two columns X and Y. I need to retrieve the data from the Y column from all the files that start with clust_rot_ using an R program.在以clust_rot_开头的文件中,有两列 X 和 Y。我需要使用 R 程序从所有以clust_rot_开头的文件中检索 Y 列中的数据。 Please help with this请帮忙
The solution goes as follows:解决方案如下:
read.table
and store it in a data.frame x使用read.table
加载第一个文件并将其存储在 data.frame xcbind(x, newdata)
在所有剩余文件的循环中,将每个文件读入临时 data.frame (例如newdata )和 append 使用cbind(x, newdata)
将其读入先前加载的数据Example with the builtin dataset iris :内置数据集iris的示例:
x <- iris[,1:2]
newdata <- iris[,3:4]
x <- cbind(x, newdata)
Try this code -试试这个代码 -
#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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.