这个问题在这里已有答案:
-
Add “filename” column to table as multiple files are read and bound 4个答案
-
How can I turn the filename into a variable when reading multiple csvs into R 4个答案
-
Importing multiple .csv files into R and adding a new column with file name 1回答
使用以下代码行可以读取多个csv并将它们保存到一个数据帧中
library(dplyr)
setwd("C:/Users/Christopher/Desktop/myfile")
temp = list.files(pattern="myfiles_.+\\.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))
aa <- mget(ls(pattern="^badges\\_\\d+")) %>%
bind_rows()
如何在每行中添加一个额外的列以获得每个文件的名称?
两个文件的示例,我提供了数据帧:
employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
myfile_1 <- data.frame(employee, salary)
myfile_2 <- read.table(header=TRUE, text="employee salary
laughter 8.50
happiness 8.44")
预期输出的示例
employee <- c('John Doe','Peter Gynn','Jolie Hope','laughter','happiness')
salary <- c(21000, 23400, 26800,8.5,8.44)
filename <- c('myfile_1','myfile_1','myfile_1','myfile_2','myfile_2')
output <- data.frame(employee, salary, filename)
输出
员工工资文件名
1 John Doe 21000.00 myfile_1
2 Peter Gynn 23400.00 myfile_1
3 Jolie Hope 26800.00 myfile_1
4笑声8.50 myfile_2
5幸福8.44 myfile_2