带动态变量名称的dplyr过滤器 [英] r dplyr filter with a dynamic variable name

查看:63
本文介绍了带动态变量名称的dplyr过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图仅选择没有NA的行:

I am trying to select only the rows without NAs:

library(dplyr)
x = data.frame(a = c(NA, 2, 3, 4))
var_a <- "a"
# This works:
x %>% filter(!is.na(a))
# That works too:
var_a <- quo(a)
x %>% filter(!is.na(!!var_a))
# But this doesn't work:
var_a <- "a"
x %>% filter(!is.na(!!var_a))

我应该在最后一行更改什么才能使其正常工作?因为我必须使用var_a<-"a". 非常感谢你!

What should I change in the last line for it to work? Because I have to work with var_a <- "a". Thank you very much!

推荐答案

它是一个字符串,因此我们可以使用sym转换为符号,然后使用!!

It is a string, so we can convert to symbol with sym and then use !!

x %>% 
   filter(!is.na(!!rlang::sym(var_a)))
#  a
#1 2
#2 3
#3 4


或者另一个选择是在filter_at中指定对象,然后进行过滤


Or another option is to specify the object in filter_at and then do the filtering

x %>% 
   filter_at(var_a, all_vars(!is.na(.)))
#  a
#1 2
#2 3
#3 4

这篇关于带动态变量名称的dplyr过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆