gpt4 book ai didi

r - 使用 Magrittr 从闭包构造函数会导致函数评估出错

转载 作者:行者123 更新时间:2023-12-04 12:33:38 28 4
gpt4 key购买 nike

当我使用 magrittr 将 x 的值传递给下面的函数时,会导致函数无法使用。为什么会这样?我有 magrittr_1.5 版本。

library(magrittr)
f <- function(x) { function(y) { x + y } }

# Case 1 (works)
f.5 <- f(5)
f.5(6) # returns 11

# Case 2 (works)
f.5 <- f(5)
6 %>% f.5 # returns 11

# Case 3 (fails)
f.5 <- 5 %>% f
6 %>% f.5 # Error in x + y (from 1) :
# non-numeric argument to binary operator

# Case 4 (fails)
f.5 <- 5 %>% f
f.5(6); # Same error as case 3

最佳答案

这是部分答案。首先,如果你评估 x 很容易让它工作。在内部匿名函数的调用环境中,

library(magrittr)
f <- function(x) { x; function(y) x + y }
f.5 <- 5 %>% f
6 %>% f.5
# [1] 11

要调查出了什么问题,请查看 x正在评估,
f <- function(x) {
function(y) {
print(sprintf("x: %s.", toString(x)))
x + y
}
}
## the failing case
fails <- 5 %>% f
6 %>% fails
# [1] "x: function (y) \n{\n print(sprintf(\"x: %s\", toString(x)))\n x + y\n}, TRUE"

它指向调用 withVisible的结果在 f ,这发生在函数时, freduce , 被称为 ( code )。在 pipe的正文中功能,有一条线,
body(magrittr:::pipe)[[2]][[3]][[10]]
# env[["freduce"]] <- freduce

哪里 freduce可用(查看 magrittr:::pipe 以获取完整上下文)。

如果将此行修改为简单地作为函数 freduce 中的实际代码(即复制 magrittr:::freduce ),它似乎有效,
## Make a modified %>% operator
mypipe <- magrittr:::pipe

## Change that line
body(mypipe)[[2]][[3]][[10]] <- quote(
env[["freduce"]] <-
function(value, function_list) {
k <- length(function_list)
if (k == 1L) {
result <- withVisible(function_list[[1L]](value))
if (result[["visible"]])
result[["value"]]
else
invisible(result[["value"]])
} else {
Recall(function_list[[1L]](value), function_list[-1L])
}
}
)

## Redefine
`%>%` <- mypipe()

## Test (now it works?!)
fails <- 5 %>% f
6 %>% fails
# [1] "x: 5"
# [1] 11

所以,这是一个部分解决方案,因为我不明白为什么要重新定义 freduce以这种方式使其工作。

关于r - 使用 Magrittr 从闭包构造函数会导致函数评估出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32293024/

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