这就是我要做的。(关键思想是将id
列的值和刚刚读入的 data.frame 放在一起调用data.frame()
.R 的回收规则将使id
列在每种情况下都具有正确的长度。)
## Set up a reproducible example
a <- tempfile()
b <- tempfile()
write.csv(head(mtcars, 2), file=a)
write.csv(tail(mtcars, 3), file=b)
fnames <- c(a,b)
## Here's the code you are looking for
do.call(rbind, lapply(fnames, function(X) {
data.frame(id = basename(X), read.csv(X))})
)
# id X mpg cyl disp hp drat wt qsec vs am gear carb
# 1 file104862dd45aa Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# 2 file104862dd45aa Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# 3 file1048d9e5764 Ferrari Dino 19.7 6 145 175 3.62 2.770 15.50 0 1 5 6
# 4 file1048d9e5764 Maserati Bora 15.0 8 301 335 3.54 3.570 14.60 0 1 5 8
# 5 file1048d9e5764 Volvo 142E 21.4 4 121 109 4.11 2.780 18.60 1 1 4 2