问题
Under certain circumstances, piping to return()
doesn't appear to behave expectedly. To demonstrate, here are 4 cases
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"
Now suppose we pipe to return
- function works as expected
funct <- function(string) {
string %>% str_replace_all(., "ef", "HHH") %>% return(.)
}
funct(string)
# [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"
Question
What is causing this behaviour and how do we get return
to return (as expected) when piped to?
Desired Output
funct <- function(string) {
string %>% str_replace_all(., "ef", "HHH") %>% return(.)
print('hi')
}
funct(string)
should return # [1] "abcdHHHghi"
Note
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)
but it did not help:
Error in return(., envir = .GlobalEnv) :
multi-argument returns are not permitted
回答1:
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"
回答2:
We can use the OP's mentioned way
funct <- function(string) {
return(string %>% string::str_replace_all(., "ef", "HHH"))
print('hi')
}
来源:https://stackoverflow.com/questions/59596950/strange-behaviour-when-piping-to-return-in-r-function