2017-03-24 33 views
0

我在列表中有几个(命名)载体:有没有简单的方法从列表中提取特定的值组合?

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

我想玩弄依赖于从另一个阵列称为梳子行它们的不同组合:

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?

但无法弄清楚如何这么多提取的实际数据... 谢谢!

+1

这是你想要的东西'as.data.frame(数据)[梳子[ ,5]]或数据[梳子[,5]]?我会使用'data.frame'而不是'list',因为数据中的向量具有相同的长度。 – mt1022

+0

不清楚给我。你可以用最终的期望输出更新你的文章吗? –

+0

感谢您的帮助...我认为一个清单更合适的原因是我在每个名称中都存储了不同的信息... – user971102

回答

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', .)) 

的第i个项目在dataMatrixList中包含对应的第i行中combs列的矩阵。然后你可以使用计算总和,产品等

rowSumsList <- lapply(dataMatrixList, function(x) apply(x, 1, sum)) 
1

这将是另一种方法,我认为给你想要什么?它会通过梳子的每一行的(非空)的元素子集划分您的数据列表返回您dataframes列表:

data_sets <- apply(combs, 
    1, 
    function(x) do.call(cbind.data.frame, data[unlist(x[x!=''])]) 
    ) 
+0

非常感谢这两个答案!他们给出了相同的解决方案,但这实际上对我所做的更好,因为我想避免软件包... – user971102

相关问题