Include .csv filename when reading data into r using list.files

前端 未结 2 1225
攒了一身酷
攒了一身酷 2021-01-14 11:28

I\'m aggregating a bunch of CSV files in R, which I have done successfully using the following code (found here):

  Tbl <- list.files(path = \"./Data/CSVs         


        
相关标签:
2条回答
  • 2021-01-14 12:19

    Here's my solution. Let me know if this helps.

    Tbl <- list.files(path = "./Data/CSVs/",
             pattern="*.csv", 
             full.names = T) %>% 
       map_df(function(x) read_csv(x, col_types = cols(.default = "c")) %>% mutate(filename=gsub(".csv","",basename(x)))) 
    
    0 讨论(0)
  • 2021-01-14 12:20

    It's difficult to know exactly what you want since the format of your data in .csv is unclear. But try gsub. Assuming you have list of your files in Tbl.list:

    library(dplyr)
    
    Tbl.list <- list.files(path = "./Data/CSVs/",
                           pattern="*.csv", 
                           full.names = T)
    

    Convert to data.frame and then mutate filename subbing out ".csv" with "":

    Tbl.df <-   data.frame( X1 = Tbl.list ) %>%
                mutate( filename_wo_ext = gsub( ".csv", "", X1 ) ) 
    

    You could also try the following, but I'm not sure it'll work. (Let's assume you have Tbl.list still). Start by changing your map_df statement to add an index column:

    map_df(~ read_csv(., col_types = cols(.default = "c")),
             .id="index") %>%
    mutate( gsub( ".csv", "", Tbl.list[as.numeric(index)] )
    

    The column index should contain a character vector [1...n]. The mutate statement will look in Tbl.list, grab the filename at index, and sub out ".csv" with "" .

    0 讨论(0)
提交回复
热议问题