Reputation: 5
Sorry in advance but I don't think i can make this entirely reproduceable as it involves reading in txt files but you can test it out quite easily with a folder of a few tabbed txt files with some random numbers in.
I have a folder with several txt files inside; I would like to read each of them into a nested list. Currently I can read 1 txt at a time with this code:
user_input <- readline(prompt="paste the path for the folder here: ")
files <- list.files(path = user_input, pattern = NULL, all.files = FALSE, full.names = TRUE)
thefiles <- data.frame(files)
thefiles
Sfiles <- split(thefiles, thefiles$files)
Sfiles
input1 <- print(Sfiles[1])
But I want to read all of the files in the given directory. I suppose it would then be a list of dataframes?
Here are some of the things i've tried:
-i guessed this would just paste all of the files in the directory but that's not entirely what i want to do.
{paste(thefiles,"/",files[[i]],".txt",sep="")
}
-this was meant to use lapply to execute read.delim on all of the files in the folder. the error it gives is: Error in file(file, "rt") : invalid 'description' argument
files_test <- list.files(path=user_input, pattern="*.txt", full.names=TRUE, recursive=FALSE)
lapply(thefiles, transform, files = read.delim(files, header = TRUE, sep = "\t", dec = "."))
-I tried it on its own aswell, also doesn't work
read.delim(files_test, header = TRUE, sep = "\t", dec = ".")
-I tried a for loop too:
test2 <- for (i in 1:length(Sepfiles){read.delim(files_test, header = TRUE, sep = "\t", dec = "."})
Is there anything obvious that I'm doing wrong? Any pointers would be appreciated Thanks
Upvotes: 0
Views: 300
Reputation: 12480
This should work if the read.delim
part is correct:
thefiles <- list.files(path = user_input, pattern = ".txt$", ignore.case = TRUE, full.names = TRUE, recursive = FALSE)
lapply(thefiles, function(f) read.delim(f, header = TRUE, sep = "\t", dec = "."))
Upvotes: 0