How to evaluate a constructed string with non-standard evaluation using dplyr?

后端 未结 2 1984
心在旅途
心在旅途 2021-01-20 03:50

I have read several guides on programming with dplyr now and I am still confused about how to solve the problem of evaluating constructed/concatenated strin

相关标签:
2条回答
  • 2021-01-20 04:38

    You might find package friendlyeval useful while learning tidy eval. It simplifies the API and makes function choice clear in cases like these.

    You have two strings you want to use as column names, so you can write:

    t <- tibble( x_01 = c(1, 2, 3), x_02 = c(4, 5, 6))
    i <- 1
    
    new <- sprintf("d_%02d", i)
    var <- sprintf("x_%02d", i)
    t %>% mutate(!!treat_string_as_col(new) := 
                   !!treat_string_as_col(var) * 2)
    

    You can convert from friendlyeval code to plain tidy eval code at any time using an RStudio addin. This may be helpful given your learning goal.

    0 讨论(0)
  • 2021-01-20 04:56

    Use sym and := like this:

    library(dplyr)
    library(rlang)
    
    t <- tibble( x_01 = c(1, 2, 3), x_02 = c(4, 5, 6))
    i <- 1
    
    new <- sym(sprintf("d_%02d", i))
    var <- sym(sprintf("x_%02d", i))
    t %>% mutate(!!new := (!!var) * 2)
    

    giving:

    # A tibble: 3 x 3
       x_01  x_02  d_01
      <dbl> <dbl> <dbl>
    1     1     4     2
    2     2     5     4
    3     3     6     6
    

    Also note that this is trivial in base R:

    tdf <- data.frame( x_01 = c(1, 2, 3), x_02 = c(4, 5, 6))
    i <- 1
    
    new <- sprintf("d_%02d", i)
    var <- sprintf("x_%02d", i)
    tdf[[new]] <- 2 * tdf[[var]]
    
    0 讨论(0)
提交回复
热议问题