2

I am creating a set of tibbles inside a lapply expression that will later be merged. I need to dynamically create variable names. Following the suggestions in this question and this , I create this minimal example:

library(tidyverse)

name_v1 <- "first_variable"
name_v2 <- "second_variable"
name_v3 <- "third_variable"

tibble(
  !!name_v1 := c(1, 2),
  !!name_v2 := c(3, 4)
)

Which obviously gives the desired output. However, I need to create a third variable using these two. Since I do not "know" the name of these variables, I need to reference the ones that were dynamically created. I tried:

tibble(
  !!name_v1 := c(1, 2),
  !!name_v2 := c(3, 4),
  !!name_v3 := !!name_v1 / !!name_v2
)
tibble(
  !!name_v1 := c(1, 2),
  !!name_v2 := c(3, 4)
) %>%
  mutate(
    !!name_v3 := !!name_v1 / !!name_v2
  )

and

tibble(
  !!name_v1 := c(1, 2),
  !!name_v2 := c(3, 4),
  !!name_v3 := name_v1 / name_v2
)

But all three give error messages. How can I access and manipulate these newly created variables?

edsandorf
  • 757
  • 7
  • 17

1 Answers1

6

You need sym:

tibble(
  !!name_v1 := c(1, 2),
  !!name_v2 := c(3, 4),
  !!name_v3 := !!sym(name_v1) / !!sym(name_v2))
)

# A tibble: 2 x 3
#   first_variable second_variable third_variable
#            <dbl>           <dbl>          <dbl>
# 1              1               3          0.333
# 2              2               4          0.5  
Bas
  • 4,628
  • 1
  • 14
  • 16