I am trying to lookup values from other columns in my data frame/tibble that are dependent on the value in column var. I can achieve this by hardcoding them in case_when()
:
library(tidyverse)
set.seed(1)
ds <- tibble(var = paste0("x", sample(1:3, 10, replace = T)),
x1 = 0:9,
x2 = 100:109,
x3 = 1000:1009)
ds %>%
mutate(result = case_when(var == "x1" ~ x1,
var == "x2" ~ x2,
var == "x3" ~ x3))
#> # A tibble: 10 x 5
#> var x1 x2 x3 result
#> <chr> <int> <int> <int> <int>
#> 1 x1 0 100 1000 0
#> 2 x3 1 101 1001 1001
#> 3 x1 2 102 1002 2
#> 4 x2 3 103 1003 103
#> 5 x1 4 104 1004 4
#> 6 x3 5 105 1005 1005
#> 7 x3 6 106 1006 1006
#> 8 x2 7 107 1007 107
#> 9 x2 8 108 1008 108
#> 10 x3 9 109 1009 1009
However, What if I don't have just 3 columns but many xn?
I found that the following works for an external variable/object:
y <- "x2"
ds %>%
mutate(result = !!sym(y))
#> # A tibble: 10 x 5
#> var x1 x2 x3 result
#> <chr> <int> <int> <int> <int>
#> 1 x1 0 100 1000 100
#> 2 x3 1 101 1001 101
#> 3 x1 2 102 1002 102
#> 4 x2 3 103 1003 103
#> 5 x1 4 104 1004 104
#> 6 x3 5 105 1005 105
#> 7 x3 6 106 1006 106
#> 8 x2 7 107 1007 107
#> 9 x2 8 108 1008 108
#> 10 x3 9 109 1009 109
But it doesn't work for an internal variable/column in a tibble:
ds %>%
mutate(result = !!sym(var))
#> Error: Only strings can be converted to symbols
Created on 2021-05-24 by the reprex package (v2.0.0)
Any ideas of how to get this to work within a data frame/tibble column are greatly appreciated.