I want to be able to rename a variable based on an argument passed into a function using dplyr::rename
. Here is the dataset.
set.seed(1)
library(tidyverse)
df <- data.frame(group = rep(letters[2:4], each = 2), score = round(rnorm(6),2))
df
# group score
# 1 b -0.63
# 2 b 0.18
# 3 c -0.84
# 4 c 1.60
# 5 d 0.33
# 6 d -0.82
I can rename the score
variable in dplyr
like so
df %>% dplyr::rename(score_7of9 = score)
# group score_7of9
# 1 b -0.63
# 2 b 0.18
# 3 c -0.84
# 4 c 1.60
# 5 d 0.33
# 6 d -0.82
Using base R I can also rename the variable by pasting a suffix to the named variable passed within a function
renameFunct <- function(data, suffix) {
colnames(data)[2] <- paste0("score", suffix)
return(data)
}
renameFunct(df, "_7of9")
# group score_7of9
# 1 b -0.63
# 2 b 0.18
# 3 c -0.84
# 4 c 1.60
# 5 d 0.33
# 6 d -0.82
However when I try to do a similar thing in the tidyverse...
renameFunct2 <- function(data, suffix) {
d <- data %>% dplyr::rename(paste0("score", !!suffix) = score)
return(d)
}
...it simply doesn't work
Honestly I find writing functions using tidyverse verbs incredibly confusing, with all the as.symbol()
, quosure()
and !!
functions. I have tried multiple combinations of these functions but can't get it to work. Can anyone enlighten me?