creating a list of files in R then forming a matrix appending the second columns

StackOverflow https://stackoverflow.com/questions/20112135

  •  03-08-2022
  •  | 
  •  

Question

I have a folder in my working directory containing 15 delimited text files (1686*2 matrix). i want to create a list of the files then make R access the files so I can import each into R. I tried using the dir() function but the list seems to capture the names of the files as character and cant access the content of the files. please help me with this. Thanks

Was it helpful?

Solution

dir() just gives you a vector with the files. You need to use read.table() and loop through the directory e.g. as follows:

# this is subdirectory where I put the test files
setwd("./csv")
# this gets a vector containing all the filenames
myfiles<-dir()
# this loops through the length of the vector (i.e. number of files)
for(i in 1:length(myfiles)){
  # this reads the data (my test file has only 4 columns, no header and is csv (use "\t" for tab))
      fileData<-read.table(file=myfiles[i],header=FALSE,sep=",",col.names=c("A","B","C","D"))
  # if the target table doesn't exist create it, else append
  ifelse(exists("targetTable"),targetTable<-rbind(targetTable,fileData),targetTable<-fileData)
}

head(targetTable)

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top