Is there an easy way to match values of a list to array in R?

爱⌒轻易说出口 提交于 2019-12-12 04:45:08

问题


I have several (named) vectors in a list:

data = list(a=runif(n = 50, min = 1, max = 10), b=runif(n = 50, min = 1, max = 10), c=runif(n = 50, min = 1, max = 10), d=runif(n = 50, min = 1, max = 10))

I want to play around with different combinations of them depending on what an array tells me, for example I want to sum across the different combinations in combs:

 var <- letters[1:length(data)]
 combs <- do.call(expand.grid, lapply(var, function(x) c("", x)))[-1,]

And get the sums for each row of these combinations. So the results for the first 8 rows would look like this:

 res = rbind(a=sum(data[["a"]]), b=sum(data[["b"]]), ab = sum(c(data[["a"]], data[["b"]])), c = sum(data[["c"]]), ac = sum(c(data[["a"]], data[["c"]])), bc = sum(c(data[["b"]], data[["c"]])), abc = sum(c(data[["a"]], data[["b"]], data[["c"]])), d=sum(data[["d"]]))

I think it is possible by extracting the list of data, by looping through each rows and each columns (I would have a variable number of columns though), but this seems quite clunky and slow, is there a better way that I am not seeing?

Thanks so much! Fra

来源:https://stackoverflow.com/questions/42967528/is-there-an-easy-way-to-match-values-of-a-list-to-array-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!