[英]querying one R data frame by matching multiple columns from a second data frame
[英]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 719B7AA2E88FE3FZ
在以clust_rot_開頭的文件中,有兩列 X 和 Y。我需要使用 R 程序從所有以clust_rot_開頭的文件中檢索 Y 列中的數據。 請幫忙
解決方案如下:
read.table
加載第一個文件並將其存儲在 data.frame xcbind(x, newdata)
將其讀入先前加載的數據內置數據集iris的示例:
x <- iris[,1:2]
newdata <- iris[,3:4]
x <- cbind(x, newdata)
試試這個代碼 -
#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.