问题
I have multiple text files (tab-delimited) generated from the same software. I initially used a loop with assign function to create variables dynamically and store them separately with the read.table function. This resulted in too many variables and was obviously time-consuming to apply operations on separate files.
I came across the lapply and fread method shown in the code below.
I don't need to merge them and they need to be separate data frames so I can compare values in the files. Using the lapply function, this was possible but the file names were not retained in any way. I found the following code from How to import multiple .csv files at once? that helped me with it. It has multiple lines and I was wondering whether there is a one-line solution for this.
foo <- function(fname){
fread(fname, skip = 5, header = TRUE, sep = " ") %>%
mutate(fn = fname)
}
all <- lapply(files, FUN = foo)
Alternatively, how do I access the specific iteration in lapply?
回答1:
We can use setNames
all <- setNames(lapply(files, foo), files)
回答2:
We can also make a general function that will set the names as the files are imported:
import_with_names <- function(files){
loaded <- list()
for (fname in files){
loaded[[fname]] <- fread(fname, skip = 5, header = TRUE, sep = " ")
}
return(loaded)
}
all <- import_with_names(files)
You can then call them by using all[[file_name]]
来源:https://stackoverflow.com/questions/59177098/reading-seperate-text-files-and-saving-them-in-a-single-variable-as-seperate-dat