我有一个列表调用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
我想将列Total
上的数据框中的Totalsamples
列添加到列表中的数据框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的第一行计数,依此类推......
mapply(function(x, y) {
out <- cbind(x, y["total"])
out
}, counts, Totalsamples, SIMPLIFY = FALSE)