【问题标题】:dplyr passing column names as a variable with is.na filterdplyr 使用 is.na 过滤器将列名作为变量传递
【发布时间】:2020-04-30 14:38:47
【问题描述】:

我知道有人问过类似的问题,我尝试了多种选择,但仍然收到错误消息。

df_construction <- function(selected_month, selected_variable){
  selected_variable_en <- rlang::enquo(selected_variable) #This was an attempt following the link

  #filter_criteria <- interp(!is.na(~y), .values = list(y = as.name(selected_variable))) This doesn't work

  df1 <- airquality %>%
    dplyr::filter(Month == selected_month,
                  !is.na(selected_variable_en))%>%
    select(Month, Day, !!selected_variable)

  return(df1)}


df1 <- df_construction(2, "Solar.R")

我的最终目标是在 Shiny 中构建它,从而让用户选择输入作为函数中的参数。

我知道filterselect 函数不应该以同样的方式处理。

我已按照以下步骤操作:https://www.brodrigues.co/blog/2016-07-18-data-frame-columns-as-arguments-to-dplyr-functions/,但由于!is.na 过滤器而没有成功。

我只想有一个数据框,其中唯一的列是所选月份的 Month 列、Day 列以及用户选择的 Ozone, Solar.R, Wind, Temp 中的任何列,没有任何 NA。

非常感谢您的帮助!!

【问题讨论】:

    标签: r dplyr na


    【解决方案1】:

    !! 通常不足以取消引用变量名。您经常需要将它们与rlang::sym 结合使用。如果要取消引用的变量不止一个,则需要使用!!!rlang::syms

    df_construction <- function(selected_month, selected_variable){
    
    df1 <- airquality %>%
        dplyr::filter(Month == selected_month,
                      !is.na(!!rlang::sym(selected_variable_en)))%>%
        select(Month, Day, selected_variable)
    
    return(df1)
    }
    

    对于select,可以直接放变量名。 dplyr 中有一个新功能可以取消引用 {{}},但它并非在所有情况下都有效。

    如果您开始在函数中编写变量名称,您可能会遇到dplyr 的困难。在这方面,data.table 更易于使用(参见a blog post I wrote on the subject

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 2017-09-14
      • 2014-05-11
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多