簡體   English   中英

在 R 中將不同文件中的多列寫入一個數據幀

[英]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 列中的數據。 請幫忙

解決方案如下:

  1. 使用read.table加載第一個文件並將其存儲在 data.frame x
  2. 在所有剩余文件的循環中,將每個文件讀入臨時 data.frame (例如newdata )和 append 使用cbind(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM