Search code examples
rdplyrtidyeval

How do I use tidyverse select when the column is input as a character object?


I'm trying to create a function which selects columns based on the input to a function:

f <- function(string) {
  quosure <- quo(!!sym(string))
  dplyr::select(data, !!quosure)
}
temp <- f("id") # returns " Error in !quosure : invalid argument type"

Strangely, this very similar looking code seems to work.

g <- function(string) {
  quosure <- quo(!!sym(string))
  dplyr::pull(data, !!quosure)
}
temp <- g("id") # Works fine

What is the difference between the first and the second function which means that the first fails and the second works?


Solution

  • It works fine for me with dplyr version '0.8.0.1'.

    library(dplyr)
    packageVersion("dplyr")
    '0.8.0.1'
    
    data <- data.frame(id= 1:10, othervariable= 11:20)
    f <- function(string) {
      quosure <- quo(!!sym(string))
      dplyr::select(data, !!quosure)
    }
    temp <- f("id")
    temp
    id
    1   1
    2   2
    3   3
    4   4
    5   5
    6   6
    7   7
    8   8
    9   9
    10 10
    

    And if you need to select (multiple) column(s) from a dataframe with a vector of characters I would rather do

    df <- data.frame(id= 1:10, othervariable= 11:20, x= 21:30)
    f <- function(data, string) {
      data[ , string]
    }
    temp <- f(data= df, string= c("id", "x"))
    temp
       id  x
    1   1 21
    2   2 22
    3   3 23
    4   4 24
    5   5 25
    6   6 26
    7   7 27
    8   8 28
    9   9 29
    10 10 30