loop through all files in a directory, read and save them in an object R

前端 未结 1 1978
挽巷
挽巷 2021-01-28 07:28

I need to loop through all files in a directory, read and save them in an object with the same name.

I tried the following but none of them worked:

files         


        
相关标签:
1条回答
  • 2021-01-28 08:13
    library(tools)
    
    files <- list.files(path=".", pattern="*.txt", all.files=T, full.names=T)
    

    The following code section comes from How can I ask a user and read those files(s) into separate dataframes?

    filelist <- lapply(files, read.table, header=F)
    names(filelist) <- paste0(basename(file_path_sans_ext(files)))
    list2env(filelist, envir=.GlobalEnv)
    

    The following code section comes from Storing multiple data frames into one data structure - R

    lapply(names(filelist), function(u) {
    assign(u, filelist[[u]]) 
    save(list=u, file=paste0(u, ".Rdata"))
    })
    
    0 讨论(0)
提交回复
热议问题