Aradhya Mudigonda
Aradhya Mudigonda

Reputation: 35

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_.csv

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. Please help with this

Upvotes: 0

Views: 926

Answers (2)

cdalitz
cdalitz

Reputation: 1277

The solution goes as follows:

  1. Load the first file with read.table and store it in a data.frame x
  2. In a loop over all remaining files, read each file into a temporary data.frame (e.g. newdata) and append it to the previously lodaed data with cbind(x, newdata)

Example with the builtin dataset iris:

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

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

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)

Upvotes: 0

Related Questions