gpt4 book ai didi

在 dmapply(ddR 包)中运行聚合函数

转载 作者:行者123 更新时间:2023-12-04 21:06:47 25 4
gpt4 key购买 nike

我想运行 aggregate dmapply 内的函数通过 ddR 提供的功能包裹。

预期结果

所需的结果反射(reflect)了通过 aggregate 生成的简单输出在基地:

aggregate(
x = mtcars$mpg,
FUN = function(x) {
mean(x, na.rm = TRUE)
},
by = list(trans = mtcars$am)
)

它产生:
  trans        x
1 0 17.14737
2 1 24.39231

尝试 - ddmapply

我想在使用 ddmapply 时达到相同的结果,如下尝试:
# ddR
require(ddR)

# ddR object creation
distMtcars <- as.dframe(mtcars)

# Aggregate / ddmapply
dmapply(
FUN = function(x, y) {
aggregate(FUN = mean(x, na.rm = TRUE),
x = x,
by = list(trans = y))
},
distMtcars$mpg,
y = distMtcars$am,
output.type = "dframe",
combine = "rbind"
)

代码失败:

Error in match.fun(FUN) : 'mean(x, na.rm = TRUE)' is not a function, character or symbol Called from: match.fun(FUN)



更新

修复 @Mike 指出的错误消除错误,但是不会产生预期的结果。编码:
# Avoid namespace conflict with other packages
ddR::collect(
dmapply(
FUN = function(x, y) {
aggregate(
FUN = function(x) {
mean(x, na.rm = TRUE)
},
x = x,
by = list(trans = y)
)
},
distMtcars$mpg,
y = distMtcars$am,
output.type = "dframe",
combine = "rbind"
)
)

产量:
[1] trans x    
<0 rows> (or 0-length row.names)

最佳答案

如果您将聚合函数更改为与您之前调用的函数一致,它对我来说很好用:FUN = function(x) mean(x, na.rm = T) .找不到原因mean(x, na.rm = T)是因为它不是一个函数(它是一个函数调用),而是 mean是一个函数。

它也会给你 NA结果除非你改变你的 x = distMtcars$mpgx = collect(distMtcars)$mpg . y 也一样。综上所述,我认为这应该适合您:

res <-dmapply(
FUN = function(x, y) {
aggregate(FUN = function(x) mean(x, na.rm = TRUE),
x = x,
by = list(trans = y))
},
x = list(collect(distMtcars)$mpg),
y = list(collect(distMtcars)$am),
output.type = "dframe",
combine = "rbind"
)

那么你可以做 collect(res)看看结果。
collect(res)
# trans x
#1 0 17.14737
#2 1 24.39231

关于在 dmapply(ddR 包)中运行聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43870520/

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