将 tapply() 与 R-buildin 数据集一起使用 mtcars 我正在尝试使用 tapply(),以查找汽车中各种变速器类型(am)和气缸数(cyl)的平均 mpg 并打印出来。
我试过使用
print(tapply(mtcars$mpg, list(mtcars$cyl, mtcars$am), mean))
但我没有得到这种形式的输出:
0 1
1 1.000 2.00000
2 3.000 4.00000
3 5.000 6.00000
相反,我得到
0 1
4 22.900 28.07500
6 19.125 20.56667
8 15.050 15.40000
我可以知道这里有什么问题吗?
我不确定为什么您希望tapply
的输出(如您的问题中所述)为
0 1
1 1.000 2.00000
2 3.000 4.00000
3 5.000 6.00000
因为您根据传输类型要求每cyl
mean(mtcars$mpg)
am
.您获得的输出中的行名是指unique(mtcars$cyl)
。现在,如果您真的希望tapply
的输出如上所述,那么您需要创建一个新列。
# function to obtain new values
myfun <- (DF) {
new <- with(DF, ifelse(cyl == 4, 1,
ifelse(cyl == 6, 3, 5)))
new <- with(DF, ifelse(am == 0, new,
ifelse(am == 1 & cyl == 4, 2*new,
ifelse(am == 1 & cyl == 6, (1+1/3)*new, 1.2*new))))
return(new)
}
mtcars$new <- myfun(mtcars)
r <- (x) noquote(format(x, nsmall = 3L))
out <- r(tapply(mtcars$new, list(mtcars$cyl, mtcars$am), mean))
rownames(out) <- c(1,2,3)
输出
> out
0 1
1 1.000 2.000
2 3.000 4.000
3 5.000 6.000