【问题标题】:Grouping ecological data in R在 R 中对生态数据进行分组
【发布时间】:2012-04-11 04:51:29
【问题描述】:

我正在查看一些生态数据(饮食)并试图找出如何按 Predator 分组。我希望能够提取数据,以便我可以查看每个捕食者的每个物种的每个猎物的重量,即计算出被例如 Predator 117 吃掉的每个物种的平均重量。我放了一个样本我的数据如下。

   Predator PreySpecies PreyWeight
1   114      10    4.2035496
2   114      10    1.6307026
3   115       1   407.7279775
4   115       1   255.5430495
5   117      10    4.2503708
6   117      10    3.6268814
7   117      10    6.4342073
8   117      10    1.8590861
9   117      10    2.3181421
10  117      10    0.9749844
11  117      10    0.7424772
12  117      15    4.2803743
13  118       1   126.8559155
14  118       1   276.0256158
15  118       1   123.0529734
16  118       1   427.1129793
17  118       3   237.0437606
18  120       1   345.1957190
19  121       1   160.6688815

【问题讨论】:

标签: r bioinformatics


【解决方案1】:

您可以使用aggregate函数如下:

aggregate(formula = PreyWeight ~ Predator + PreySpecies, data = diet, FUN = mean)

#   Predator PreySpecies PreyWeight
# 1      115           1 331.635514
# 2      118           1 238.261871
# 3      120           1 345.195719
# 4      121           1 160.668881
# 5      118           3 237.043761
# 6      114          10   2.917126
# 7      117          10   2.886593
# 8      117          15   4.280374

【讨论】:

    【解决方案2】:

    有几种不同的方法可以得到你想要的:

    1. aggregate 函数。可能是你所追求的。

      aggregate(PreyWeight ~ Predator + PreySpecies, data=dd, FUN=mean)
      
    2. tapply: 非常有用,但只是将变量除以单个因子,因此,我们需要使用粘贴命令创建一个需要的联合因子:

      tapply(dd$PreyWeight, paste(dd$Predator, dd$PreySpecies), mean)
      
    3. ddplyplyr 包的一部分。很有用。值得学习。

      require(plyr)
      ddply(dd, .(Predator, PreySpecies), summarise, mean(PreyWeight))
      
    4. dcast:输出更多的是表格格式。 reshape2 包的一部分。

      require(reshape2)
      dcast(dd, PreyWeight ~ PreySpecies+ Predator, mean, fill=0)
      

    【讨论】:

      【解决方案3】:

      mean(data$PreyWeight[data$Predator==117]);

      【讨论】:

      • 这可能不如这里给出的其他答案那么实用......如果你想获得所有捕食者物种的结果,你需要一整套这样的陈述,或者一个 for 循环...作为教学示例更有用(我认为)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多