Loading many files at once?

前端 未结 3 1772
萌比男神i
萌比男神i 2020-11-28 04:04

So let\'s say I have a directory with a bunch of .rdata files

file_names=as.list(dir(pattern=\"stock_*\"))

[[1]]
[1] \"stock_1.rdata\"

[[2]]
[1] \"stock_2.         


        
3条回答
  •  甜味超标
    2020-11-28 04:41

    For what it's worth, the above didn't exactly work for me, so I'll post how I adapted that answer:

    I have files in folder_with_files/ that are prefixed by prefix_pattern_, are all of type .RData, and are named what I want them to be named in my R environment: ex: if I had saved var_x = 5, I would save it as prefix_pattern_var_x.Data in folder_with_files.

    I get the list of the file names, then generate their full path to load them, then gsub out the parts that I don't want: taking it (for object1 as an example) from folder_with_files/prefix_pattern_object1.RData to object1 as the objname to which I will assign the object stored in the RData file.

    file_names=as.list(dir(path = 'folder_with_files/', pattern="prefix_pattern_*"))
    file_names = lapply(file_names, function(x) paste0('folder_with_files/', x))
    out = lapply(file_names,function(x){
      env = new.env()
      nm = load(x, envir = env)[1]
      objname = gsub(pattern = 'folder_with_files/', replacement = '', x = x, fixed = T)
      objname = gsub(pattern = 'prefix_pattern_|.RData', replacement = '', x = objname)
      # print(str(env[[nm]]))
      assign(objname, env[[nm]], envir = .GlobalEnv)
      0 # succeeded
    } )
    

提交回复
热议问题