两个因素的变量均值 [英] Mean of variable by two factors

查看:188
本文介绍了两个因素的变量均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

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)

我可以使用以下方法通过方法获得每个物种的样本数:

I can use the following to get a count of the number of samples of each species by method:

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

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

How do I also get the mean length by method for each species?

推荐答案

我个人会使用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

对于您可能需要的所有内容:

for everything together you may want:

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

这篇关于两个因素的变量均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆