将多个.csv文件导入R并添加文件名的新列 [英] Importing multiple .csv files into R and adding a new column with file name

查看:224
本文介绍了将多个.csv文件导入R并添加文件名的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有80个独立的.csv文件,这些文件具有相同的列和标题,可以使用以下命令将其导入和rbind作为一个数据帧:

I have 80 separate .csv files that have the same columns and headers that I was able to import and rbind as one dataframe using the following commands:

 file_names <- dir("~/Desktop/data") 
 df <- do.call(rbind,lapply(file_names,read.csv))

但是我想添加一个新变量(名称),该变量标识每个观察结果来自哪个.csv文件。因此,例如,对于来自 NY.csv文件的所有观察结果,此变量名称将为 NY,对于来自 DC.csv文件的所有观察结果变量为 DC,等等...
有没有办法在每个.csv上不手动添加此新列的方法?谢谢!

But I would like to add a new variable ("name") that identifies from which .csv file each observation came from. So for example, this variable "name" would be "NY" for all the observations from the 'NY.csv' file and "DC" for all observations from the 'DC.csv' file, etc... Is there any way to do this without adding this new column manually on each .csv? Thanks!

推荐答案

应该这样做:

file_names <- dir("~/Desktop/data") 
df <- do.call(rbind, lapply(file_names, function(x) cbind(read.csv(x), name=strsplit(x,'\\.')[[1]][1])))

这篇关于将多个.csv文件导入R并添加文件名的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆