Strange behaviour when piping to return() in R function?

♀尐吖头ヾ 提交于 2020-08-07 15:08:10

问题


Under certain circumstances, piping to return() doesn't appear to behave expectedly. To demonstrate, here are 4 cases

Suppose we define a function that returns 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!