1

This is reproducible minimal dataset and function because it is not the point. my real function is very complicated but that's not the point in here.



id <- 1:30
x<-rnorm(30,1,10)
y<-rnorm(30,1,10)

data<-data.frame(id,x,y)

try<-function(data,
             x,
             y){
  
  require(tidyverse)
  
  data<-data %>%
    mutate(new=x+y)
  
  return(data)
}



the feedback I got was:

1)Generally, it's a good practice to avoid using require() or library() within a function.

however, I am using tidyverse grammar (%>% etc ) in my user-defined function so if I do not use require(), I am very confused what option that I have.

Tube
  • 177
  • 5
  • 1
    R does not have a good built-in answer to this question: this is a fundamental deficiency of the language. The non-built-in answer is to use [‘**box**’](https://klmr.me/box/) (specifically, in your case, replace `library(tidyverse)` with `box::use(dplyr[...])`; and [never use `require` anyway](https://stackoverflow.com/a/51263513/1968)). – Konrad Rudolph Apr 22 '23 at 11:04
  • 1
    So my feedback, do not use pipes (neither your magrittr pipes nor base) in functions. Instead of using a library call, you can use double colons, e.g. `dplyr::mutate`. – jay.sf Apr 22 '23 at 11:04

1 Answers1

1

Generally, it's good practice to list all dependencies in one place. If your analysis consists of only one script, then the dependencies should be listed at the top of the script. If you're using an R project, you can use a separate script for this, or even better, use renv. If you're working on an R package, the dependencies are listed in the package documentation.

So, in your case, you can:

1: Load the necessary package on top of the script:

library(tidyverse)
id <- 1:30
x<-rnorm(30,1,10)
# rest of code

2. Call only the necessary function using "::":

# rest of code
try<-function(data,
             x,
             y){
  
  data<-data %>%
    dplyr::mutate(new=x+y)
  
  return(data)
}

The second approach can be more suitable if you're using only a handful of functions from a given package. Also, note that for dplyr::mutate to work, you need to have the dplyr package installed.