使用list.files将数据读入R时包含.csv文件名 [英] Include .csv filename when reading data into r using list.files
本文介绍了使用list.files将数据读入R时包含.csv文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在R中聚集一堆CSV文件,已使用以下代码成功完成了此操作(找到
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/",
pattern="*.csv",
full.names = T) %>%
map_df(~read_csv(., col_types = cols(.default = "c")))
我想将.csv文件名(理想情况下不带文件扩展名)作为Tbl中的一列包括在内.我找到了使用plyr的解决方案,但是我想坚持使用dplyr,因为plyr会导致我的代码进一步出现毛刺.
I want to include the .csv filename (ideally without the file extension) as a column in Tbl. I found a solution using plyr, but I want to stick with dplyr as plyr causes glitches further down my code.
有什么办法可以在上述代码中添加一些内容,以使R将文件名包含在Tbl $ filename中?
Is there any way I can add something to the above code that will tell R to include the file name in Tbl$filename?
非常感谢!
推荐答案
这是我的解决方案.让我知道是否有帮助.
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))))
这篇关于使用list.files将数据读入R时包含.csv文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文