gpt4 book ai didi

r - plyr 转换后不返回新变量

转载 作者:行者123 更新时间:2023-12-02 00:33:30 27 4
gpt4 key购买 nike

我正在尝试学习如何在 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

最佳答案

只做两个改变

  1. 去掉函数内的打印命令,返回中位数
  2. 按照 Joshua 的建议添加 medianAB = testfunc1(ab)

你完成了!

这是带有输出的简化代码

library(plyr)
highab <-subset(baseball, ab >= 600)
baseball3 <-ddply(highab, .(id), transform, medianAB = median(ab))
summary(baseball3$medianAB)

Min. 1st Qu. Median Mean 3rd Qu.
Max. 600.0 612.0 621.5 623.1 631.5 677.0

关于r - plyr 转换后不返回新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5668345/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com