How can I read multiple csvs and retain the number in the file name for each?

心已入冬 提交于 2020-04-10 06:00:12

问题


I have multiple csv files in a folder none of which have a header. I want to preserve the order set out by the number at the end of the file. The file names are "output-1.csv", "output-2.csv" and so on. Is there a way to include the file name of each csv so I know which data corresponds to which file. The answer [here][1] gets close to what I want.

library(tidyverse)

#' Load the data ----
mydata <-
  list.files(path = "C:\\Users\\Documents\\Manuscripts\\experiment1\\output",  
   pattern = "*.csv") %>%
  map_df( ~ read_csv(., col_names = F))
mydata

回答1:


You can use:

library(tidyverse)

mydata <- list.files("C:\\Users\\Documents\\Manuscripts\\experiment1\\output", 
pattern = ".csv$", full.names = T) %>% 
  set_names(str_sub(basename(.), 1, -5)) %>% 
  map_dfr(read_csv, .id = "file")


来源:https://stackoverflow.com/questions/59717739/how-can-i-read-multiple-csvs-and-retain-the-number-in-the-file-name-for-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!