为什么dplyr filter()在函数内不起作用(即使用变量作为列名)? [英] Why doesn't dplyr filter() work within function (i.e. using variable for column name)?

查看:146
本文介绍了为什么dplyr filter()在函数内不起作用(即使用变量作为列名)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用dplyr函数对数据进行过滤,分组和变异的函数。基本的管道序列在功能之外非常有用,这就是我使用真实列名的地方。将其放在列名是变量的函数中,其中一些函数可以工作,但某些函数不是最著名的dplyr :: filter()。例如:

A function for filtering, grouping and mutating data with dplyr functions. Basic pipe sequence works great outside a function, that is where I use the true column names. Put it in a function where the column name is a variable and some of the functions work but some don't most notably dplyr::filter(). For example:

var1 <- c('yes', NA, NA, 'yes', 'yes', NA, NA, NA, 'yes', NA, 'no', 'no', 'no', 'maybe', NA, 'maybe', 'maybe', 'maybe')

var2 <- c(1:18)

df <- data.frame(var1, var2)

这很好用(即过滤NA):

This works fine (i.e. filters NA's):

df%>%filter(!is.na(var1))

...但这不是:

x <- "var1"

df%>%filter(!is.na(x))

...但是这样做:

df%>%select(x)

需要NA

尝试get( x),不好,然后切片:

Tried get("x"), no good, and slicing:

df[!is.na(x),]

。 ..也没有好处。

关于如何传递变量以在函数内部(或外部)进行过滤以及为什么变量与其他dplyr函数一起工作的任何想法?

Any ideas on how to pass a variable to filter inside (or outside) a function and why a variable is working with other dplyr functions?

推荐答案

我们可以使用 sym 转换为符号,然后使用 UQ 评估

We can use the sym to convert to a symbol and then with UQ evaluate it

library(rlang)
library(dplyr)
df %>%
   filter(!is.na(UQ(sym(x))))
#     var1 var2
#1    yes    1
#2    yes    4
#3    yes    5
#4    yes    9
#5     no   11
#6     no   12
#7     no   13
#8  maybe   14
#9  maybe   16
#10 maybe   17
#11 maybe   18

这篇关于为什么dplyr filter()在函数内不起作用(即使用变量作为列名)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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