我使用的是随机生成的数据框:
dat1 <- merge(data.frame(Gender = rep("MALE",5),height = sample(70:100,5)),
data.frame(Gender = rep("FEMALE",5),height = sample(50:100,5)),by.x = c("Gender","height"),
by.y = c("Gender","height"),all = TRUE)
当我使用tapply
函数时,我得到了结果:
tapply(dat1$height,dat1$Gender,mean)
MALE FEMALE
85.6 77.8
但是当我使用aggregate
函数时,它会导致:
aggregate(height~gender , data= dat1, mean)
gender height
1 FEMALE 77.4
2 MALE 86.0
和by
函数产生与tapply
相同的结果:
by(dat1$height,dat1$Gender,mean)
dat1$Gender: MALE
[1] 85.6
-------------------------------------------------------------------------------------------------
dat1$Gender: FEMALE
[1] 77.8
我知道我已经使用了示例函数,每次执行时我都会更改值,但结果的差异仅在于单次执行。
有人可以帮忙吗?