在R函数中管道传递给return()时会出现奇怪的行为? [英] Strange behaviour when piping to return() in R function?
问题描述
在某些情况下,输送到 return()
的行为似乎不符合预期。为了说明这一点,这里有4种情况
Under certain circumstances, piping to return()
doesn't appear to behave expectedly. To demonstrate, here are 4 cases
假设我们定义了一个函数,该函数返回
返回 str_replace_all
Suppose we define a function that return
s the result of str_replace_all
library(stringr)
library(dplyr)
string <- letters[1:9] %>% paste0(collapse="")
funct <- function(string) {
return(string %>% str_replace_all(., "ef", "HHH"))
}
funct(string)
# [1] "abcdHHHghi"
现在假设我们通过管道传递给 return
-函数按预期工作
Now suppose we pipe to return
- function works as expected
funct <- function(string) {
string %>% str_replace_all(., "ef", "HHH") %>% return(.)
}
funct(string)
# [1] "abcdHHHghi"
但是如果我们在之后添加一些任意命令,则返回
,我们不获得预期的输出( [1] abcdHHHghi
)
But if we add some arbitrary commands after the return
, we do not get the expected output ([1] "abcdHHHghi"
)
funct <- function(string) {
string %>% str_replace_all(., "ef", "HHH") %>% return(.)
print('hi')
}
funct(string)
# [1] "hi"
请注意,如果我们不通过管道传递返回
, 做查看预期的行为
Note that if we don't pipe to return
, we do see the expected behaviour
funct <- function(string) {
return(string %>% str_replace_all(., "ef", "HHH"))
print('hi')
}
funct(string)
# [1] "abcdHHHghi"
问题
是什么原因导致这种现象以及如何获得<$ c
Question
What is causing this behaviour and how do we get return
to return (as expected) when piped to?
funct <- function(string) {
string %>% str_replace_all(., "ef", "HHH") %>% return(.)
print('hi')
}
funct(string)
应返回#[1] abcdHHHghi;
基于类似的奇怪行为,当管道连接到 ls()
,我尝试过
Based on similarly strange behaviour when piping to ls()
, I tried
funct <- function(string) {
string %>% str_replace_all(., "ef", "HHH") %>% return(., envir = .GlobalEnv)
print('hi')
}
funct(string)
但这没有帮助:
Error in return(., envir = .GlobalEnv) :
multi-argument returns are not permitted
推荐答案
在链的RHS上,退货
面临一些评估问题。参见 github问题线程。
return
faces some evaluation issue when it is on RHS of the chain. See this github issue thread.
如果必须使用返回
,最安全的方法是使用
If you have to use return
the safest way is to use
funct <- function(string) {
return(string %>% stringr::str_replace_all("ef", "HHH"))
print('hi')
}
funct(string)
#[1] "abcdHHHghi"
这篇关于在R函数中管道传递给return()时会出现奇怪的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!