Remove columns the tidyeval way

百般思念 提交于 2019-12-18 16:48:40

问题


I would like to remove a vector of columns using dplyr >= 0.7

library(dplyr)
data(mtcars)

rem_cols <- c("wt", "qsec", "vs", "am", "gear", "carb")
head(select(mtcars, !!paste0("-", rem_cols)))

Error: Strings must match column names. Unknown columns: -wt, -qsec, -vs, -am, -gear, -carb

dplyr < 0.7 worked as follows:

head(select_(mtcars, .dots = paste0("-", rem_cols)))
#                    mpg cyl disp  hp drat
# Mazda RX4         21.0   6  160 110 3.90
# Mazda RX4 Wag     21.0   6  160 110 3.90
# Datsun 710        22.8   4  108  93 3.85
# Hornet 4 Drive    21.4   6  258 110 3.08
# Hornet Sportabout 18.7   8  360 175 3.15
# Valiant           18.1   6  225 105 2.76

I've tried about all combinations of rlang:syms(), !!, !!!, quo and enquo that I can think of... help!?


回答1:


We can use one_of

 mtcars %>%
        select(-one_of(rem_cols))



回答2:


I would also use one_of() in this case but more generally you have to create calls to - with the symbols as argument.

# This creates a single call:
call("-", quote(a))

# This creates a list of calls:
syms(letters) %>% map(function(sym) call("-", sym))

You can then splice the list of calls with !!!




回答3:


The difficulty I had in doing precisely this task lead to me writing a package, friendlyeval, to simplify the tidy eval API. Here's an idea on how to do this using that:

library(friendlyeval)
library(dplyr)
data(mtcars)

rem_cols <- c("wt", "qsec", "vs", "am", "gear", "carb")
minus_cols <- paste0("-",rem_cols)
# [1] "-wt"   "-qsec" "-vs"   "-am"   "-gear" "-carb"

head(select(mtcars, !!!friendlyeval::treat_strings_as_exprs(minus_cols)))

#                    mpg cyl disp  hp drat
# Mazda RX4         21.0   6  160 110 3.90
# Mazda RX4 Wag     21.0   6  160 110 3.90
# Datsun 710        22.8   4  108  93 3.85
# Hornet 4 Drive    21.4   6  258 110 3.08
# Hornet Sportabout 18.7   8  360 175 3.15
# Valiant           18.1   6  225 105 2.76

The one trap here is that you must use treat_strings_as_exprs() instead of treat_strings_as_cols(), since "-wt" is an expression involving a column name, not an actual column name.




回答4:


drop = c("wt", "qsec", "vs", "am", "gear", "carb")
 mtcars %>% 
    select_(.dots= setdiff(names(.),drop))


来源:https://stackoverflow.com/questions/45100518/remove-columns-the-tidyeval-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!