将列表中的列与其他列表绑定

Cbind columns from lists with other list

我有一个列表调用 Totalsamples,在列表中我有 9 个数据框,如下所示:

year  total
2015   100
2016   115
2017   150
2018   155

我有其他列表调用 counts,在列表中我有 9 个数据框,如下所示:

year   A   B   C   Sum    
2015   15  10  5   30          
2016   10  13  12  35                   
2017   5   8   15  28             
2018   9   10  5   24

我想将列表 Totalsamples 中数据框的列 Total 添加到列表 counts

中的数据框

所以我在列表的每个数据框中都得到了这个 counts

year   A   B   C   Sum  Total   
2015   15  10  5   30    100      
2016   10  13  12  35    115                
2017   5   8   15  28    150         
2018   9   10  5   24    155

我试过了

counts<- lapply(counts, function (x) cbind(x, Total = Totalsamples[[x]][total]))   

但我想我索引错了列表 Totalsamples。 你能告诉我正确的做法吗?

谢谢

是的,你是对的,你索引错了。您正在尝试使用 data.frame 对 TotalSamples 进行索引以获取计数。

您可以使用其中之一。

counts =  lapply(1:length(counts), function (i) cbind(counts[[i]], Total = Totalsamples[[i]][total])) 

或者

for(i in 1:length(counts)){
  counts[[i]]$Total = Totalsamples[[i]]$total
}

或者您可以:

counts = mapply(function(x, y) cbind(x, y[,-1]), counts, Totalsamples)

您可以使用 mapply().

首先,一些示例数据:

Totalsamples <- list(
    data.frame(year = 1990:2000, total = rpois(11, 100)),
    data.frame(year = 1990:2000, total = rpois(11, 100))
  )
counts <-list(
    data.frame(
      year = 1990:2000,
      a = rpois(11, 10),
      b = rpois(11, 20)),
    data.frame(
      year = 1990:2000,
      a = rpois(11, 10),
      b = rpois(11, 20)
    )
  )

counts

中的列求和
counts <- lapply(counts, function(x) {
  x$sum <- rowSums(x[c("a", "b")])
  x
})

现在使用mapply()进行cbind。 注意:这要求所有数据帧中的行顺序相同,并且数据帧的顺序要匹配。即它将 Totalsamples 中第一个 data.frame 的第一行与计数中第一个 data.frame 的第一行进行 cbind,依此类推...

mapply(function(x, y) {
  out <- cbind(x, y["total"])
  out
}, counts, Totalsamples, SIMPLIFY = FALSE)