【问题标题】:Mean of variable by two factors两个因素的变量平均值
【发布时间】:2013-05-21 07:09:35
【问题描述】:

我有以下数据:

a <- c(1,1,1,1,2,2,2,2)
b <- c(2,4,6,8,2,3,4,1)
c <- factor(c("A","B","A","B","A","B","A","B"))
df <- data.frame(
    sp=a,
    length=b,
    method=c)

我可以使用以下方法来统计每个物种的样本数量:

n <- with(df,tapply(sp,method,function(x) count(x)))

如何通过方法获得每个物种的平均长度?

【问题讨论】:

  • 顺便说一句,只是为了节省您的一些输入,with(df,tapply(sp,method,count)) 在您的示例中可以正常工作。

标签: r tapply


【解决方案1】:

我个人会使用aggregate:

aggregate(length ~ sp, data = df, FUN= "mean" )
# by species only
#     sp length
#1  1    5.0
#2  2    2.5

aggregate(length ~ sp + method, data = df, FUN= "mean" )
    # by species and method
#  sp method length
#1  1      A      4
#2  2      A      3
#3  1      B      6
#4  2      B      2

你可能想要的一切:

aggregate(length ~ method, data = df, function(x) c(m = mean(x), counts = length(x)) )

# counts and mean for each method
#  method length.m length.counts
#1      A      3.5           4.0
#2      B      4.0           4.0

【讨论】:

    【解决方案2】:

    图书馆 plyr 对这样的东西非常有帮助

    library(plyr)
    new.df <- ddply(df, c("method", "sp"), summarise,
                    mean.length=mean(length),
                    max.length=max(length),
                    n.obs=length(length))
    

    给你

    > new.df
      method sp mean.length max.length n.obs
    1      A  1           4          6     2
    2      A  2           3          4     2
    3      B  1           6          8     2
    4      B  2           2          3     2
    

    更多示例请访问http://www.inside-r.org/packages/cran/plyr/docs/ddply

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      相关资源
      最近更新 更多