Search code examples
rnaming

naming lists within for loop using paste0 and get/eval, parse


Straight to the question. as1_list

I am trying to name data.frames in a list using name() and paste() but I am having trouble assigning them

num_fu = c('1','2','3','4','5','6','7','8','9')
as <- data.frame()

for (i in num_fu){
           assign(paste0("flnames", i), list.files(path = paste0("C:/Users/thepr/Documents/data/as", i), pattern = "\\.csv", full.names = TRUE))
           assign(paste0("as", i, "_list"), lapply(get(paste0("flnames", i)),
                                          function(x){base::as.data.frame(read.csv(x))}))
           
           nm <- gsub(".csv", "", basename(get(paste0("flnames", i)))) %>% str_sub(., 1,6)

nm returns

nm 1 "as1_01" "as1_02" "as1_03" "as1_04" "as1_05" "as1_07" "as1_08" "as1_09" "as1_11" "as1_13" [11] "as1_14" "as1_15" "as1_99"

and

names(as1_list) returns

> names(as1_list)
NULL

I tried get(paste0 ...

names(get(paste0("as", i, "_list"))) <- nm

this returns error: Error in names(get(paste0("as", i, "_list"))) <- nm : target of assignment expands to non-language object

so I tried

names(eval(parse(text = paste0("as", i, "_list")))) <- nm

and this occurred: Error in names(eval(parse(text = paste0("as", i, "_list")))) <- nm : target of assignment expands to non-language object

I have also tried assign() function using both of the above codes.

assign(names(get(paste0("as", i, "_list"))), nm)

Returns: Error in assign(names(get(paste0("as", i, "_list"))), nm) : invalid first argument

and

assign(names(eval(parse(text = paste0("as", i, "_list")))), nm)

Returns: Error in assign(names(eval(parse(text = paste0("as", i, "_list")))), nm) : invalid first argument

Please help. Thank you.


Solution

  • As specified in your comment, the following will give you a list of dataframes, each from a single CSV-file (starting with "as") and named with the filename excluding extension:

    data_dir <- 'C:/Users/thepr/Documents/data/'
    file_names <- list.files(data_dir, pattern = 'as.*\\.csv')
    
    list_of_dataframes <- 
      file_names |>
      Map(f = \(fn) read.csv(file.path(data_dir,fn))) |>
      setNames(nm = gsub('\\.csv', '', file_names))
    

    Note the use of Map to operate on a list (of file names, in this case) and avoid any for loop (generally a good idea in R).