一元运算符的无效参数-错误消息-负dplyr ::用向量选择

时间:2018-07-24 16:35:02

标签: r dplyr

我一直在使用向量来肯定地对数据帧进行子集化,并且效果很好。现在,我想使用相同的向量来否定该数据帧的子集。

我收到一条错误消息(一元运算符的无效参数),但是在谷歌搜索后,我仍然不明白这意味着什么。

感谢您的帮助!

# Starting point 
df_main <- data.frame(coat=c(1:5),hanger=c(1:5),book=c(1:5),dvd=c(1:5),bookcase=c(1:5),
                      clock=c(1:5),bottle=c(1:5),curtains=c(1:5),wall=c(1:5))
df_keep <- data.frame(keep_var=c("coat","hanger","book","wall","bottle"),othvar=c("r","w","r","w",NA))



# Vector
library(dplyr)
keep.vec <- as.character(
  (df_keep %>% dplyr::filter(is.na(othvar) | othvar == 'r'))$keep_var
)


# Attempts at using vector for negative subsetting 
df_main %>% dplyr::select(-keep.vec)
df_main[-keep.vec, ] 

1 个答案:

答案 0 :(得分:1)

我们可以在one_of

中使用辅助函数tidyselect包装它
df_main %>%
    select(-one_of(keep.vec))
#  hanger dvd bookcase clock curtains wall
#1      1   1        1     1        1    1
#2      2   2        2     2        2    2
#3      3   3        3     3        3    3
#4      4   4        4     4        4    4
#5      5   5        5     5        5    5

或者另一个选择是setdiff

df_main %>%
    select(setdiff(names(.), keep.vec))

也可以在tidyverse

之外使用
df_main[setdiff(names(df_main), keep.vec)]