1

I thought of simplifying my code a bit and tried to engage with the world of custom build functions. I build the following dummy:

library(dplyr, tidyverse)
##
string <- c("car", "train", 'bike', 'plain')
speed1 <- runif(4, min = 0, max = 10000)
speed2 <- runif(4, min = 0, max = 10000)
n1  <- sample(1:100, 4)
n2  <- sample(1:100, 4)
##
df <- data.frame(string, speed1, speed2, n1, n2)
df

Basically, I want to do simple operations of the following type:

df <- df%>%
 dplyr::mutate(speed1_n1 = paste0(format(speed1, big.mark   = ",") , '\n(' , format(n1, big.mark   = ",") , ')'))
df

I can build a function:

my_fun <- function(dataf, V1, V2){
 dataf <- dataf%>%
dplyr::mutate(speed1_n1 = paste0(format(V1, big.mark   = ",") , '\n(' , format(V2, big.mark   = ",") , ')'))}

df<-df%>%my_fun( df$speed1, df$n1)
df

However, the variable names needs to be generated dynamically from the called variable names similar to the question here, but within a function. I cannot manually specify mutate(speed1_n1=.... Something, like: !!paste('speed1', 'n1', sep = "_"):=, but with the variable / column names and not in quotes.

MsGISRocker
  • 588
  • 4
  • 21

1 Answers1

2

We may use the arguments as unquoted and use {{}} for evaluation

my_fun <- function(dataf, V1, V2){
   dataf %>%
   dplyr::mutate("{{V1}}_{{V2}}" := paste0(format({{V1}}, big.mark   = ",") ,
      '\n(' , format({{V2}}, big.mark   = ",") , ')'))
}

-testing

my_fun(df, speed1, n1)
string   speed1   speed2 n1 n2       speed1_n1
1    car 7886.962 3218.585 37 83 7,886.962\n(37)
2  train 9534.978 5524.649 98 34 9,534.978\n(98)
3   bike 6984.790 9476.838 60 55 6,984.790\n(60)
4  plain 6543.198 2638.609  9 53 6,543.198\n( 9)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I wonder how to call for a dynamic composite variable name also on the right hand side of the equations. If I were to substitute ```format({{V2}},``` by ```format("{{V1}}_plus_{{V2}}",``` it does not work. I tried ````as.name()```` with ````paste0()````, ````eval(parse(text = paste0()))```` and and ... . See extended question [here!](https://stackoverflow.com/questions/69003844/using-a-composite-to-call-a-variable-dynmically-in-custom-build-function-with-dp) – MsGISRocker Aug 31 '21 at 18:40