Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass vector of column names to paste() within mutate (dplyr)

Tags:

r

dplyr

rlang

I'm trying to write a function that takes as one of its arguments a vector of column names from user. The column names will be used to specify what columns of the dataframe will be pasted together to form a new column within dplyr::mutate. I tried to collapse the elements of argument vector first and then use the collapsed string in mutate - this is wrong. See that latest attempt below. I made other attempts but I'm not understanding the new quo, enquo, UQ, !!!, !!, and so on within dplyr. Can someone show what I need to do?

df <- data.frame(.yr = c("2000", "2001", "2002"), .mo = c("12", "01", "02"), .other = rnorm(3))
cols <- colnames(df)[1:2]

do_want <- df %>%
  mutate(new = paste(.yr, .mo, sep = "-"))

my_func <- function(dat, vars){
  .vars <- paste(vars, collapse = ",")

  result <- dat %>%
    mutate(new = paste(.vars, sep = "-" ))
  return(result)
}

my_func(dat = df, vars = cols)

edit: this is my attempt at using quo and !! in the function definition. the result is a column of repeated string ".yr,.mo"

my_func <- function(dat, vars){
  .vars <- quo(paste(vars, collapse = ","))

  result <- dat %>%
    mutate(new = paste(!!.vars, sep = "-" ))
  return(result)
}
like image 678
mb158127 Avatar asked Jan 03 '23 14:01

mb158127


2 Answers

Because you have a list of strings, you can use rlang::syms in your function to take the strings and turn them into symbols. Then you can use !!! to splice the arguments together to put into paste.

my_func <- function(dat, vars){
     .vars <- rlang::syms(vars)

     result <- dat %>%
          mutate(new = paste(!!!.vars, sep = "-" ))
     return(result)
}

my_func(dat = df, vars = cols)

   .yr .mo     .other     new
1 2000  12 -0.2663456 2000-12
2 2001  01  0.5463433 2001-01
3 2002  02 -1.3133078 2002-02
like image 121
aosmith Avatar answered Jan 14 '23 01:01

aosmith


Use unite.

names <- iris %>% colnames()
iris %>% mutate(new = paste(names)) #Error
iris %>% unite("new",names,remove=F) #OK
like image 33
Takuro Ikeda Avatar answered Jan 14 '23 01:01

Takuro Ikeda