使用下面的数据和在R中工作,我想要生成一个新的数据序列列表,其中每个数据都是基于4种不同值的惟一组合。在下面的数据中,我有10种不同的Taxon (很多有多个复制条目),我想一次为所有4种组合选择4种类型。我相信在这10种Taxon中,应该有210种不同的组合(当采样没有替换和顺序是不重要的)。因此,我最终想要一个包含210个数据文件的列表,每个列表包含4个Taxon的不同组合(每个Taxon的所有复制行)!
虽然选择是基于Taxon向量的,但我希望新的数据格式包含其他列的信息。例如,如果选择"Aphididae.sp.3“,我希望新的dataframe也有-25.92(C),1.69(N),sap(func.group),herbivore(trophic.group)列在旁边。
到目前为止,我使用"combn“函数来使用"unique”命令生成4个分类单元的所有组合,但是我无法获得包含在其中的所有其他列的信息,而且它没有为每个分类单元提供所有复制条目!我很感谢你的帮助!
我的代码:
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发布于 2013-11-27 17:14:53
combos应该是字符向量的4x210矩阵。如果您使用的是原始代码而不是原始代码,请使用:
combos<-combn(unique(as.character(df$Taxon)), 4) # factors would be converted您应该能够使用apply将这些向量传递给一个子设置函数。
combdf <- apply(combos, 2, function(vec) df[ df$Taxon %in% vec, ] )在测试过程中,我发现原来的矩阵搞砸了,因为我把分类单元作为因子,因此需要在as.character调用之前调用unique。直到尝试apply调用时,我才看到这一点,因为我得到了210个条目,但其中大多数都是空的。
发布于 2013-11-27 17:28:18
lapply(ncol(combos), function(x) df[df$Taxon %in% combos[,x],])https://stackoverflow.com/questions/20248407
复制相似问题