有没有一种简单的方法可以从列表中提取特定的值组合?

时间:2017-03-24 04:10:06

标签: r list combinations

我在列表中有几个(命名的)向量:

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))

我想根据另一个名为combs的数组中的行来使用它们的不同组合:

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

我希望能够提取每个组合,以便我可以使用这些组合创建的向量 所有这些都是为了能够将函数应用于提取的每一行,然后应用于这些数据帧的每个组合。例如:

 # Row 5 is "a", "c"
 combs[5,] 
 # Use this information to extract this particular combination from my data:
 # by hand it would be:
 res_row5 = cbind(data[["a"]], data[["c"]])
 # Extract another combination
 # Row 11 is "a", "b", "d"
 combs[11,] 
 res_row11 = cbind(data[["a"]], data[["b"]], data[["d"]])
 # So that I can apply functions to each row across all these vectors
 res_row_5_func = apply(res_row5, 1, sum)
 # Apply another function to res_row11
 res_row_5_func = apply(res_row11, 1, prod)
 # Multiply the two, do other computations which can do as long as I have extracted the right vectors

我在这里问了一个非常相似的问题:Is there an easy way to match values of a list to array in R?

但无法弄清楚如何提取实际数据...... 非常感谢!

2 个答案:

答案 0 :(得分:1)

您可以做的是首先生成索引data中相关条目的向量列表:

library(magrittr)
combList <- lapply(1:nrow(combs), function(ii) combs[ii,] %>% unlist %>% setdiff(""))

然后,您可以使用此列表为data中的列编制索引,并生成所需矩阵的新列表:

dataMatrixList <- lapply(combList, function(indVec) data[indVec] %>% do.call('cbind', .)) 

dataMatrixList中的第i个条目包含一个矩阵,其中的列对应combs中的第i行。然后,您可以使用

计算总和,产品等
rowSumsList <- lapply(dataMatrixList, function(x) apply(x, 1, sum))

答案 1 :(得分:1)

这将是另一种方法,我认为你想要的是什么?它将通过按每行梳子的(非空)元素对数据列表进行子集化来返回数据帧列表:

data_sets <- apply(combs,
    1, 
    function(x) do.call(cbind.data.frame, data[unlist(x[x!=''])])
    )
相关问题