简体   繁体   中英

Using for loop to name vector

I am using a for loop to read in several tables, while reading in these tables I would like to generate lists from a specific column in each data frame and name that list using a variable.

The idea is to use a list such as Names in example below, which can then be used to assign vector names to lists as they are brought in.

Names <- list("1","2","3")


Tables <- list.files(".",recursive = T, pattern = ".csv", full.names=T)

for (file in Tables)
{
 print(file)
 df <- read.csv(file, header =T)
 list <- list(df$1)
}

What is the best appraoch to end up with a results that gives me lists named list_1, list_2, and list_3 from the example above?

thanks for any help you can provide.

Here is a solution using tidyverse .

library(tidyverse)    

Tables <- list.files(path = ".",
               recursive = T,
               pattern = ".csv",
               full.names = T) %>% 
      map(~read_csv(.)) %>% 
      set_names(., nm = paste0("list_", Names))

list2env(Tables, envir = .GlobalEnv)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM