如何将向量附加到 data.frames 的列表?

How to append a vector to a list of data.frames?

如何 cbind/append 一个指向 data.frames 列表的向量?

l <- list(data.frame(a=c(1,2,3), b=c(1,2,3)), data.frame(a=c(1,2,3,4), b=c(1,2,3,4)))
l
file_name <- c("myfile.txt", "yourfile.txt")
file_name

我试过了:

lapply(l, function(x) cbind(l[[x]], fname = rep(file_name, each = nrow(l[[x]]))))

但是我得到一个错误:

Error in l[[x]] : invalid subscript type 'list'

我们可以使用 Mapcreate a new column 'fname' for each of thelist` 元素,方法是将相应的 'file_name' 附加到它

Map(cbind, l, fname = file_name)

如果我们使用lapply,则循环遍历list

的序列
lapply(seq_along(l), function(i) transform(l[[i]], fname = file_name[i]))

只是为了确保..您有以下列表 data.frames..

l <- list(data.frame(a=c(1,2,3), b=c(1,2,3)), data.frame(a=c(1,2,3,4), b=c(1,2,3,4)))
l
[[1]]
  a b
1 1 1
2 2 2
3 3 3

[[2]]
  a b
1 1 1
2 2 2
3 3 3
4 4 4

你最终想要将一个向量(每个列表不同)绑定到列表中的所有 data.frames.. 所以你想要

[[1]]
  a b v
1 1 1 a
2 2 2 b
3 3 3 c

[[2]]
  a b v
1 1 1 a
2 2 2 b 
3 3 3 c
4 4 4 d

我们可以做的一个技巧是首先使用 rbindlist 将所有帧放在一起..并保留它们的 ID

L = rbindlist(l,idcol = TRUE)

假设我们还有一个列表要附加到每个 data.frame

v = list(data.frame(v = letters[1:3]), data.frame(v = LETTERS[1:4]))
V = rbindlist(v)

现在我们可以做一个简单的 cbind,然后使用我们创建的 .id 拆分列表

result = cbind(L,V)
final_result = split(result,on = ".id")

    $`1`
   .id a b v
1:   1 1 1 a
2:   1 2 2 b
3:   1 3 3 c

$`2`
   .id a b v
1:   2 1 1 A
2:   2 2 2 B
3:   2 3 3 C
4:   2 4 4 D

我们在那里还有一个 .id 列..但是去掉那个应该不会太麻烦..