dplyr_0.5.0.9002, passing string as variable name to select

30 views
Skip to first unread message

msquatrito

unread,
Apr 18, 2017, 1:06:24 PM4/18/17
to manipulatr
Hi, 
I'm trying to pass a string as a variable name to `select()`. It works fine with `select_()`, however, now it is deprecated.
I'm not sure how to do it with the new way `select` is suppose to work.

df <- tibble(a = 1:5, b = 6:10)
var1
<- "a"

either of  this works fine:

df %>% select(a)
df
%>% select_(var1)

and this doesn't work:

df %>% select(var1) # I knew this already would not work

# Error: var1: must resolve to integer column positions, not string


df
%>% select(!!var1)

# Error: "a": must resolve to integer column positions, not string

df
%>% select(UQ(var1))

# Error: "a": must resolve to integer column positions, not string

Honestly, I'm still struggling a little in wrapping my head around standard and non standard evaluation.

What is the proper approach to solve this issue?

Thanks in advance!

Massimo

Hadley Wickham

unread,
Apr 18, 2017, 6:12:53 PM4/18/17
to msquatrito, manipulatr
You've got two options:

1. Convert the string to a symbol:

df %>% select(!!sym(var1))

1. Use the existing one_of() helper

df %>% select(one_of(var))

Hadley
> --
> You received this message because you are subscribed to the Google Groups
> "manipulatr" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to manipulatr+...@googlegroups.com.
> To post to this group, send email to manip...@googlegroups.com.
> Visit this group at https://groups.google.com/group/manipulatr.
> For more options, visit https://groups.google.com/d/optout.



--
http://hadley.nz
Reply all
Reply to author
Forward
0 new messages