I have a tibble:
library(tibble)
library(dplyr)
(
data <- tibble(
a = 1:3,
b = 4:6,
mycol = c('a', 'b', 'a')
)
)
#> # A tibble: 3 x 3
#> a b mycol
#> <int> <int> <chr>
#> 1 1 4 a
#> 2 2 5 b
#> 3 3 6 a
Using dplyr::mutate
I'd like to create a new column called value
which uses a value from either column a
or b
, depending on which column name is specified in the mycol
column.
(
desired <- tibble(
a = 1:3,
b = 4:6,
mycol = c('a', 'b', 'a'),
value = c(1, 5, 3)
)
)
#> # A tibble: 3 x 4
#> a b mycol value
#> <int> <int> <chr> <dbl>
#> 1 1 4 a 1
#> 2 2 5 b 5
#> 3 3 6 a 3
Here we're just using the values from column a
all the time.
data %>%
mutate(value = a)
#> # A tibble: 3 x 4
#> a b mycol value
#> <int> <int> <chr> <int>
#> 1 1 4 a 1
#> 2 2 5 b 2
#> 3 3 6 a 3
Here we're just assigning the values of mycol
to the new column rather than getting the values from the appropriate column.
data %>%
mutate(value = mycol)
#> # A tibble: 3 x 4
#> a b mycol value
#> <int> <int> <chr> <chr>
#> 1 1 4 a a
#> 2 2 5 b b
#> 3 3 6 a a
I've tried various combinations of !!
, quo()
, etc. but I don't fully understand what's going on under the hood in terms of NSE.
@Jaap has marked this as a duplicate but I'd still like to see a dplyr/tidyverse approach using NSE rather than using base R if possible.