![](/img/trans.png)
[英]Using “combn” to create list of dataframes for all combinations of variables selected and columns for variables not selected
[英]Using “combn” to create list of dataframes for all combinations of a variable
使用下面的數據框並在R中工作,我想生成一個新數據幀列表,其中每個數據幀基於我的Taxon向量的4個不同值的唯一組合。 在下面的數據框中,我有10個不同的Taxon(許多有多個復制條目),我想一次選擇4個Taxon,對於4的所有組合。我相信這些10個Taxon中應該有210個不同的4個Taxon組合(無需更換時采樣,訂單並不重要)。 所以最終我想要一個包含210個數據幀的列表,每個數據幀包含4個Taxon的不同組合(每個Taxon的所有復制行)!
雖然選擇基於Taxon向量,但我希望新數據框包含其他信息列。 例如,如果選擇“Aphididae.sp.3”,我希望新數據框中還列出了-25.92(C),1.69(N),sap(func.group),草食動物(trophic.group)並肩作戰。
到目前為止,我使用“combn”函數使用“unique”命令生成4個taxon的所有組合,但是我無法獲得包含在其中的所有其他信息列,並且它不會為每個組提供所有復制條目類群! 我會感激任何幫助!
我的代碼:
combos<-combn(unique(df$Taxon),4)
DF:
Taxon C N func.group trophic.grp
1 Aphididae.sp.3 -25.92 1.69 sap herbivore
2 Aphididae.sp.3 -25.91 1.78 sap herbivore
3 Aphididae.sp.3 -26.05 1.74 sap herbivore
4 Cicadellidae.mixed.juvs -28.94 1.19 sap herbivore
5 Cicadellidae.mixed.juvs -29.25 2.24 sap herbivore
6 Cicadellidae.mixed.juvs -28.17 1.88 sap herbivore
7 Cicadellidae.mixed.juvs -28.29 1.94 sap herbivore
8 Cicadellidae.sp.1 -27.69 2.25 sap herbivore
9 Cicadellidae.sp.1 -27.67 2.41 sap herbivore
10 Cicadellidae.sp.1 -26.65 3.26 sap herbivore
11 Cicadellidae.sp.1 -28.30 3.20 sap herbivore
12 Cicadellidae.sp.1 -28.08 1.88 sap herbivore
13 Cicadellidae.sp.2 -26.59 2.89 sap herbivore
14 Cicadellidae.sp.3 -26.82 5.16 sap herbivore
15 Cicadellidae.sp.4 -26.54 3.46 sap herbivore
16 Cicadellidae.sp.4 -26.55 4.05 sap herbivore
17 Cicadellidae.sp.4 -27.20 3.14 sap herbivore
18 Cicadellidae.sp.4 -26.48 3.80 sap herbivore
19 Cicadellidae.sp.5 -27.54 4.17 sap herbivore
20 Cicadellidae.sp.5 -27.18 3.43 sap herbivore
21 Cicadellidae.sp.5 -27.46 4.03 sap herbivore
22 Cicadellidae.sp.6 -26.71 1.09 sap herbivore
23 Cicadellidae.sp.6 -26.33 1.56 sap herbivore
24 Cicadellidae.sp.6 -25.59 0.59 sap herbivore
25 Cicadellidae.sp.6 -25.07 0.84 sap herbivore
26 Cicadellidae.sp.6 -26.56 0.97 sap herbivore
27 Cicadellidae.sp.7 -25.84 1.08 sap herbivore
28 Cicadellidae.sp.7 -24.96 1.36 sap herbivore
29 Cicadellidae.sp.7 -26.15 1.90 sap herbivore
30 Cicadellidae.sp.7 -26.58 2.63 sap herbivore
31 Cicadellidae.sp.8 -28.02 2.28 sap herbivore
32 Cicadellidae.sp.8 -27.90 2.01 sap herbivore
33 Cicadellidae.sp.8 -27.70 1.92 sap herbivore
34 Cicadellidae.sp.8 -26.85 1.04 sap herbivore
combos
應該是4 x 210矩陣的字符向量。 如果您使用以下代碼而不是原始代碼:
combos<-combn(unique(as.character(df$Taxon)), 4) # factors would be converted
您應該能夠將這些向量傳遞給子集化函數,並apply
:
combdf <- apply(combos, 2, function(vec) df[ df$Taxon %in% vec, ] )
在測試過程中,我發現原始矩陣搞砸了,因為我把Taxons留在了因素中,因此在unique
之前需要as.character
調用。 我沒有看到這個,直到嘗試apply
因為我有210件物品,但大多數是空的。
lapply(ncol(combos), function(x) df[df$Taxon %in% combos[,x],])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.