gpt4 book ai didi

r - 两个因子的变量均值

转载 作者:行者123 更新时间:2023-12-04 01:49:25 27 4
gpt4 key购买 nike

我有以下数据:

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)))

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

最佳答案

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

关于r - 两个因子的变量均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16664119/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com