2017-03-24 40 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

相關問題