我正在尝试了解如何使用 apply 功能,我遇到了本教程:http : //nsaunders.wordpress.com/2010/08/20/a-brief-introduction-to-apply-in-r/看起来简洁明了,但我马上就遇到了问题。他们给出的第一个例子来证明 apply 是:
> # create a matrix of 10 rows x 2 columns
> m <- matrix(c(1:10, 11:20), nrow = 10, ncol = 2)
> # mean of the rows
> apply(m, 1, mean)
[1] 6 7 8 9 10 11 12 13 14 15
这似乎很基本,但我想我会试一试。这是我的结果:
> # create a matrix of 10 rows x 2 columns
> m <- matrix(c(1:10, 11:20), nrow = 10, ncol = 2)
> # mean of the rows
> apply(m, 1, mean)
Error in FUN(newX[, i], ...) : unused argument(s) (newX[, i])
不用说,我迷路了……
为了提供更多信息,我尝试了教程中提供的另一个示例并得到了正确的结果。这种情况的不同之处在于该函数在 apply 函数中被明确说明:
apply(m, 1:2, function(x) x/2)
[,1] [,2]
[1,] 0.5 5.5
[2,] 1.0 6.0
[3,] 1.5 6.5
[4,] 2.0 7.0
[5,] 2.5 7.5
[6,] 3.0 8.0
[7,] 3.5 8.5
[8,] 4.0 9.0
[9,] 4.5 9.5
[10,] 5.0 10.0
sessionInfo() 输出如下:
R version 2.15.3 (2013-03-01)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] tools_2.15.3
以及冲突的输出(详细信息 = TRUE)
$.GlobalEnv
[1] "edit" "mean"
$`package:utils`
[1] "edit"
$`package:methods`
[1] "body<-" "kronecker"
$`package:base`
[1] "body<-" "kronecker" "mean"