为何R语言中aggregate与tapply函数计算均值结果存在差异?
tapply() and aggregate() give different mean results? Let's break down why you're seeing mismatched results between these two R functions:
The Core Issue: Random Data Generation
The key reason for the differing means is that you're working with two separate versions of your dat1 dataset.
Your code to create dat1 relies on the sample() function, which produces new random height values every time you run it:
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 )
If you generated dat1 once for the tapply() call, then re-ran the dat1 creation code before using aggregate(), you're calculating means on two entirely different sets of random heights. That's why the numbers don't line up.
How to Verify This
Run all your code in one continuous sequence, so both functions use the exact same dat1:
# Generate dat1 ONCE 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 ) # Run both functions on the same dataset tapply(dat1$height, dat1$Gender, mean) aggregate(height ~ Gender, data = dat1, mean)
You'll see both functions return identical mean values for each gender.
A Quick Syntax Note
Also, in your aggregate() code you wrote height~gender (lowercase 'g'), but your data frame uses Gender (uppercase 'G'). This would normally throw an error because R can't find a column named gender. It's likely a typo in your question—always make sure you use the exact column name that matches your dataset.
内容的提问来源于stack exchange,提问作者satendra nath

