Reading seperate text files and saving them in a single variable as seperate dataframes

╄→尐↘猪︶ㄣ 提交于 2020-01-24 21:47:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!