Grouping environmental data in R

I am looking at some environmental data (diet) and trying to figure out how to group the Predator. I would like to be able to extract the data so that I can look at the weights of each individual prey for each species for each predator i.e. Calculate the average weight of each species eaten by, for example, a predator 117. I have put a sample of my data below.

   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

      

+3


source to share


3 answers


You can use the function aggregate

like this:



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

      

+7


source


There are several ways to get the desired result:



  • Function aggregate

    . It is possible that you are after.

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

  • tapply

    : Very useful, but only divides the variable by one factor, so we need to create a co-factor with the insert command:

    tapply(dd$PreyWeight, paste(dd$Predator, dd$PreySpecies), mean)
    
          

  • ddply

    : part of a package plyr

    . Very helpful. It's worth learning.

    require(plyr)
    ddply(dd, .(Predator, PreySpecies), summarise, mean(PreyWeight))
    
          

  • dcast

    : the output is more in table format. Part of the package reshape2

    .

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

+5


source


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

0


source







All Articles