我正在尝试学习如何在 R/plyr 中编写函数。我知道有更简单的方法可以完成我在下面展示的操作,但这不是重点。
在下面的示例中,PLYR 不会将新变量返回到我的新数据框
library(plyr)
highab <-subset(baseball, ab >= 600)
testfunc1 <-function(x) {
print(x) #just to show me that the vector does get into the function. Works fine.
medianAB <- median(x)
print(medianAB) #just to prove that medianAB was calculated correctly. Works fine
}
baseball3 <-ddply(highab, .(id), transform, testfunc1(ab))
str(baseball3$medianAB) #No medianAB
我错过了什么明显的东西?
R version 2.12.2 (2011-02-25)
Platform: x86_64-pc-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_CA.UTF-8 LC_NUMERIC=C LC_TIME=en_CA.UTF-8 LC_COLLATE=en_CA.UTF-8
[5] LC_MONETARY=C LC_MESSAGES=en_CA.UTF-8 LC_PAPER=en_CA.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] grid splines stats graphics grDevices utils datasets methods base
other attached packages:
[1] foreign_0.8-42 ggplot2_0.8.9 proto_0.3-9.1 reshape_0.8.4 plyr_1.4.1 rms_3.3-0 Hmisc_3.8-3
[8] survival_2.36-5 stringr_0.4
loaded via a namespace (and not attached):
[1] cluster_1.13.3 lattice_0.19-23 tools_2.12.2