0

I want to select the column named "b" in a tibble. "b" is the value of a variable called col_name.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
col_name <- "b" # the column to select

df <- tibble(a = c(1,2,3), b = c(2,4,6))

df$b
#> [1] 2 4 6
# But I want to use a variable to dynamically select the column
df$col_name
#> Warning: Unknown or uninitialised column: `col_name`.
#> NULL
Created on 2020-10-12 by the reprex package (v0.3.0)
4
  • 1
    Maybe df[ , col_name ] ?
    – zx8754
    Oct 12, 2020 at 17:37
  • 1
    If you want to stay in dplyr, then maybe df %>% pull(!!col_name)
    – zx8754
    Oct 12, 2020 at 17:40
  • Of course. Thank you and sorry.
    – sbac
    Oct 12, 2020 at 17:42
  • 2
    No worries, duplicates help put similar content together, please do not delete.
    – zx8754
    Oct 12, 2020 at 17:43

1 Answer 1

2
df %>% select( {{ col_name }} )
#or
df %>% select( !!col_name )
#or
df[[col_name]]

in last case you will obtain a vector instead of data frame

2
  • Please do not rush with answer, if it sounds too easy, most likely it was already asked before, please search.
    – zx8754
    Oct 12, 2020 at 17:42
  • @ricardo-villalba And what about mutate(!! col_name = )? What would be the right syntax?
    – sbac
    Oct 12, 2020 at 18:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.