Add “filename” column to table as multiple files are read and bound

前端 未结 6 2111
轮回少年
轮回少年 2020-11-27 20:54

I have numerous csv files in multiple directories that I want to read into a R tribble or data.table. I use \"list.files()\" with the recursive argument set to TRUE to creat

6条回答
  •  离开以前
    2020-11-27 21:25

    You can build a filenames vector based on "sites" with the exact same length as tbl and then combine the two using cbind

    ### Get file names
    filenames <- list.files(path, full.names = TRUE, pattern = fileptrn, recursive = TRUE)
    sites <- str_extract(filenames, "[A-Z]{2}-[A-Za-z0-9]{3}")
    
    ### Get length of each csv
    file_lengths <- unlist(lapply(lapply(filenames, read_csv), nrow))
    
    ### Repeat sites using lengths
    file_names <- rep(sites,file_lengths))
    
    ### Create table
    tbl <- lapply(filenames, read_csv) %>% 
      bind_rows()
    
    ### Combine file_names and tbl
    tbl <- cbind(tbl, filename = file_names)
    

提交回复
热议问题