【问题标题】:How to write a function that includes pipes using functions from the srvyr package?如何使用 srvyr 包中的函数编写一个包含管道的函数?
【发布时间】:2019-07-12 15:44:45
【问题描述】:

我有一个调查,我试图按年份分组,并计算某些变量的总数。我需要使用不同的变量执行此操作大约 20 次,所以我正在编写一个函数,但我似乎无法正常工作,即使它在函数外工作正常。

这很好用:

 mepsdsgn %>% group_by(YEAR) %>% summarise(tot_pri = survey_total(TOTPRV)) %>% select(YEAR, tot_pri)

当我尝试一个功能时:

total_calc <- function(x) {mepsdsgn %>% group_by(YEAR) %>% summarise(total = survey_total(x)) %>% select(YEAR, total)}

total_calc(TOTPRV)

我收到此错误:stop_for_factor(x) 中的错误:找不到对象“TOTPRV”

【问题讨论】:

  • TOTPRV 是某物的名称(字符串,如变量名)还是实际对象?
  • 它是数据框 mepsdsgn 中的列名
  • 那么你应该在调用函数时将它作为字符串引用....这是问题之一,修复它。然后你可以在你的函数中将它称为mepsdsgn[[x]]
  • total_calc % group_by(YEAR) %>% summarise(tot =survey_total(mepsdsgn[[x]])) %>% select(YEAR, tot) } total_calc(mepsdsgn[[TOTPRV]]) ``` 和 total_calc &lt;- function(x) {mepsdsgn %&gt;% group_by(YEAR) %&gt;% summarise(tot = survey_total(x)) %&gt;% select(YEAR, tot)} total_calc(mepsdsgn[[TOTPRV]]) 仍然得到错误错误在 stop_for_factor(x) : object 'TOTPRV' not found
  • medium.com/optima-blog/… 我认为这会解决问题,但包是 sryvr 而不是 dplyr

标签: r pipe


【解决方案1】:

想通了:

total_fun % group_by(YEAR) %>% summarise(total =survey_total(!!sym(col), na.rm = TRUE)) %>% select(YEAR, total) }

【讨论】:

    【解决方案2】:

    我建议做几件事,见下文

    # first try to make a working minimal example people can run in a new R session
    library(magrittr)
    library(dplyr)
    dt <- data.frame(y=1:10, x=rep(letters[1:2], each=5))
    
    # simple group and mean using the column names explicitly
    dt %>% group_by(x) %>% summarise(mean(y))
    
    # a bit of googling showed me you need to use group_by_at(vars("x")) to replicate
    # using a string input
    # in this function, add all arguments, so the data you use - dt & the column name - column.x
    foo <- function(dt, column.x){
      dt %>% group_by_at(vars(column.x)) %>% summarise(mean(y))
    }
    
    # when running a function, you need to supply the name of the column as a string, e.g. "x" not x
    foo(dt, column.x="x")
    

    我不使用dplyr,所以可能有更好的方法

    【讨论】:

      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-05
      • 2021-03-26
      • 2011-04-30
      相关资源
      最近更新 更多