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)
zx8754
  • 52,746
  • 12
  • 114
  • 209
sbac
  • 1,897
  • 1
  • 18
  • 31

1 Answers1

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

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