Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

r - Forcing dplyr to evaluate passed symbol / quosure when conflicting with existing column name

Problem

I want to string of a column name to dplyr::arrange in a form am <- "cyl". The purpose is to sort by column cyl.

Desired outcome

dplyr::arrange(mtcars, cyl)

Attempts

am <- "cyl"

1) rlang::quo

dplyr::arrange(mtcars, !!rlang::quo(am))

Sorted by am not cyl.

2) rang::ensym

dplyr::arrange(mtcars, !!rlang::ensym(am))

Sorted by am not cyl.

3) Culry Curly

dplyr::arrange(mtcars, {{am}})

Not sorted.


Background

In actual function I'm sorting data frame by index column I'm creating. The variable with column name is called index_column. I want protect myself from, albeit highly unlikely, scenario of actual data containing index_column. I could solve that using make.names and scanning for unique column names but I'm more interested in solving the problem above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It would be sym

out2 <-  dplyr::arrange(mtcars, !!rlang::sym(am))

-testing with OP's expected

out1 <- dplyr::arrange(mtcars, cyl)
identical(out1, out2)
#[1] TRUE

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...