如何以编程方式过滤dplyr中的列? [英] How to programmatically filter columns in dplyr?

查看:99
本文介绍了如何以编程方式过滤dplyr中的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不希望在调用函数之前指定列,我该如何创建一个将NA值删除的函数?

How would I create a function that drops NA values in a column if I don't want to specify the column until the function is called?

minimal_case <- function(column_name = "a") {
  enquo_name <- enquo(column_name)

  example <- tibble(a = c(NA, 1))

  print(filter(example, !is.na(a)))

  print(filter(example, !is.na(rlang::UQ(enquo_name))))

}

第一个打印语句的输出为:

The output of the first print statement is:

# A tibble: 1 x 1
      a
  <dbl>
1     1

第二个打印语句的输出为:

The output of the second print statement is:

# A tibble: 2 x 1
      a
  <dbl>
1    NA
2     1

如何获得第二个打印语句以匹配第一个打印语句?

How do I get the second print statement to match the first?

推荐答案

似乎column_name参数是一个字符串.在这种情况下,您可以使用rlang::sym:

It seems the column_name parameter is a string. In that case, you can use rlang::sym:

minimal_case <- function(column_name = "a") {
    example <- tibble(a = c(NA, 1))

    print(filter(example, !is.na(a)))

    print(filter(example, !is.na(!!rlang::sym(column_name))))

}

这篇关于如何以编程方式过滤dplyr中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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