【问题标题】:function with variable column name具有可变列名的函数
【发布时间】:2020-03-29 19:20:28
【问题描述】:

我有一个函数,我反复使用它来汇总个人信息(在我的数据集中具有唯一 ID。由于这些数据的排列方式,有时 ID 列有一个名称,而其他时候它有另一个名称。而不是每个数据集都有不同的函数,我试图在我的函数中有一个 IDtype 字段,这样我就可以在每个数据集中指定 ID 字段所在的列。但是,我在下面的函数中不断收到以下错误:

fun <- function(df, IDtype) {
  df %>%
    group_by(species, IDtype, site) %>%
    summarize(tsMean = mean(ts)) %>%
    arrange(IDtype, tsMean)
}

dfSum <- (fun(data, IDtype = id) #also tried with id in quotes ("id"), but I get the same error 

Error: Column `IDtype` is unknown 

如何修复此功能?

【问题讨论】:

    标签: r function dplyr


    【解决方案1】:

    data.table感兴趣的人可以使用以下语法:

    library(data.table)
    fun <- function(df, IDtype){
       return(
          df[, .(tsMean = mean(ts)), by = c("species", IDtype, "site")][order(get(IDtype), get("tsMean")]
          )
    }
    setDT(data)
    fun(data, IDtype = "id")
    

    您使用 get() 函数取消引用名称

    【讨论】:

      【解决方案2】:

      我们可以使用curly-curly 运算符 ({{}}) 来评估未加引号的值

      fun <- function(df, IDtype) {
        df %>%
           group_by(species, {{IDtype}}, site) %>%
           summarize(tsMean = mean(ts)) %>%
           arrange({{IDtype}}, tsMean)
          }
      
      fun(data, IDtype = id)
      

      【讨论】:

      • 谢谢@akrun!这一定是一个创纪录的时间响应,因为我什至不能接受你的回答。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多