DevanDevak DevanDevak - 10 months ago 34
R Question

Error in reading multple text files from directory in R

I would like to read multiple text files from my directory the files are arranged in following format


following is the script that i have written


array <- c()
for (file in dir(/media/dev/Daten/Task1/subject1/t1)) # path to the directory where .txt files are located

row4 <- read.table(file=list.files(pattern ="regional_vol*.txt"),
header = FALSE,
row.names = NULL,
skip = 3, # Skip the 1st 3 rows
nrows = 1, # Read only the next row after skipping the 1st 3 rows
sep = "\t") # change the separator if it is not "\t"
array <- cbind(array, row4)

I am incurring following error

Error in file(file, "rt") : invalid 'description' argument

kindly suggest me where i was wrong in the script

Answer Source

I think this should do it. It assumes that all files have header :

mydir<- "~/Desktop/a"
# read full paths
myfiles<- list.files(mydir,pattern = "regional_vol*",full.names=T)
# initialise the dataframe from first file 

df<- read.csv( myfiles[1], header = T, skip = 0, nrows = 4)[-c(1:3),]
#read all the other files and update dataframe
#we read 4 lines to read the header correctly, then remove 3
ans<- lapply(myfiles[-1], function(x){  read.csv( x, header = T, skip = 0, nrows = 4)[-c(1:3),]       })
#update dataframe
lapply(ans, function(x){df<<-rbind(df,x)}  )
#this should be the required dataframe