Trouble passing string to represent variable name in function

I'm still confused by all the embrace, enquo, unquo, !! etc.

I want to create a different tibble based on the day of the week.

library(tidyverse)
library(lubridate)

Monday <- c("Bob", "Jim", "Jane")
Tuesday <- c("Roberto", "Maria", "Xochil")

# Assume today is Monday
expected <- tibble(staff = Monday)

days <- function(dow){
    tibble(staff = !!dow). # I don't know how to wrap dow
}


dayofweek <- wday(today(), label = TRUE, abbr = FALSE)

days(dayofweek)



There should be some way to wrap 'dow' in the function so that it takes the dayofweek and when it is Monday, creates a tibble based on the Monday list.

I don't understand why this works, so if someone could explain it, I'd appreciate it, but here seems to be a solution.

days <- function(dow){
    tibble(staff = !!sym(dow))

}


dayofweek <- wday(today(), label = TRUE, abbr = FALSE) %>% as.character()


days(dayofweek)

Dow is a character string
Sym ... treat it as a symbol
Symbols stand in for values assigned to them
!! Gives you the value assigned to the dow symbol

What about if I want to pass an expression rather than a column name? e.g. pass say "year(survey_date)" or even "Year=year(survey_date)". I know the following won't work:

gensumm <- function(df, expr) {
dplyr::summarise(df, !!sym(expr))
}

I know I could use eval(parse(text=expr)), but then the resulting tibble will have as its column name "eval(parse(text=expr))" rather than "Year" or "year(survey_date)"

Can this be done?

Regards

James

I just posted something about enquo, so I don't totally understand. But a solution is to convert the expression to a symbol and use !! in the summarize for the LHS of the summarize and then eval(parse()). You also have to use the walrus := instead of a regular equals sign.

gensumm <- function(df, expr) {
  dplyr::summarise(df, 
                   !!sym(expr) := eval(parse(text = expr))
                   )
}

If you don't want the expression function as the name of the column then I would supply a string too. Instead of having to parse out the specific relevant information from the expression.

gensumm2 <- function(df, expr, col_name) {
  dplyr::summarise(df, 
                   !!sym(col_name) := eval(parse(text = expr))
  )
}
2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.