I have the following code
library(dplyr)
p <- data.frame(a = rep(0:2, times = 5)) %>%
mutate(a1 = a == 1,a2 = a == 2)
I want to put the expressions in mutate
in a function (or a list, I do not really care) so that I define them before running mutate
I tried this:
mutatemy=function(){
(a1=a==1,a2=a==2)
}
p <- data.frame(a = rep(0:2, times = 5)) %>%
mutate(mutatemy())
which does not work of course.
Ideally, I should be able to flexibly put all possible mutate
combinations such as the use of across
.
How could I achieve this.
The background is that I mutate inside a function and I want the user to allow specifying exactly what to mutate without manipulating the function.
Here is a simplified example of what I want to eventually achieve.
mainfunction <- function(data=data){
#somecode...
data2<- data %>% mutate(r=a*a, # hardcoded
userinput) # here I want to allow the user to decide what else to mutate
return(data2)
}
## user supplies data
data= data.frame(data.frame(a=rep(0:2,times=5))
## and the desired manipulations based on the supplied dataset
userinput <- (a1=a==1)
## and then applies this function
mainfunction(data)
#somecode...
Thanks a lot! Julian