【问题标题】:function for data.table to perform group by actionsdata.table 执行分组操作的函数
【发布时间】:2020-11-23 17:19:13
【问题描述】:

我有一个示例 data.table 数据

sampledt<- data.table("BP"=c(seq(c(1:3)),c(1:2)) ,"STATUS"=c(rep("CASE",5),rep("CONTROL",5) ), "value"=c(0.8,0.9,0.10,0.9,0.10))

有列 - BP - 碱基对,状态是案例和控制。值是按状态分层的每个 BP 的值。我需要获得按 BP 和 STATUS 分组的值的平均值,我使用以下代码获得:

sampledt[,.("meaned_group"=mean(value)),by=.(BP,STATUS)] ## this achieves desired results 

但是,我想创建一个函数来执行此任务。有时我需要简单地通过BPSTATUS 列来获取平均值。或者我对总和感兴趣而不是平均。

join_group_datatable<-function(temp_datat,temp_namecolumn,column_value,func_join, list_groupby){

##temp_datat - temp data.table
## temp_namecolumn - output column name - grouped_mean or meaned_group 
## column_value column on which function needs to be applied 
## func_join - function may be mean, may be sun
## list_groupby - vector of group

temp_datat[,.(temp_namecolumn=func_join(column_value) , by=.(list_groupby))]

}

我设置了函数并运行以下代码行:

join_group_datatable(sampledt,"meaned_group","value",mean,c("BP","STATUS"))

这给了我错误/警告:

Warning message:
In mean.default(column_value) :
  argument is not numeric or logical: returning NA

输入数据的类别。表值是数字。我无法理解如何使函数传递列名、函数并获得所需的结果。

【问题讨论】:

    标签: r function group-by data.table


    【解决方案1】:

    如果你用以下内容替换你的函数体,它应该可以工作。

    temp_datat[, setNames(.(func_join(get(column_value))), temp_namecolumn), by = mget(list_groupby)]
    

    这使用get/mgetsetNames 将函数参数传递到data.table 调用范围内的相关位置。

    【讨论】:

      猜你喜欢
      • 2019-01-13
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      相关资源
      最近更新 更多