I have a list call Totalsamples
, inside the list I have 9 data frames that look like this:
year total
2015 100
2016 115
2017 150
2018 155
I have other list call counts
, inside the list I have 9 data frames that look like this:
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
I want to add the column Total
from the data frames on list Totalsamples
, to the data frames on the list counts
So that I get this in every data frame from the list 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
I tried this
counts<- lapply(counts, function (x) cbind(x, Total = Totalsamples[[x]][total]))
But I guess I'm indexing wrong the list Totalsamples
.
Can you tell me how to do it correctly?
Thank you
Yes you are right you are indexing wrong. You are trying to index TotalSamples with the data.frame for counts.
Instead you can use one of these.
counts = lapply(1:length(counts), function (i) cbind(counts[[i]], Total = Totalsamples[[i]][total]))
Or
for(i in 1:length(counts)){
counts[[i]]$Total = Totalsamples[[i]]$total
}
Or you can:
counts = mapply(function(x, y) cbind(x, y[,-1]), counts, Totalsamples)