建议避免"如果"自定义函数中的语句带有可选参数

时间:2018-06-05 01:56:51

标签: r data.table ellipsis

考虑以下对象dt

library(data.table)

set.seed(12345)

dt <- data.table(Gender = sample(x = c("Male", "Female"), size = 10, replace = T), 
           Department = sample(x = c("Sales", "Marketing"), size = 10, replace = T), 
           Hours = runif(n = 10, 6, 8))

dt

    Gender Department    Hours
 1:   Male  Marketing 7.981743
 2: Female  Marketing 6.142455
 3: Female  Marketing 7.284672
 4:   Male  Marketing 6.114810
 5:   Male  Marketing 6.067997
 6:   Male  Marketing 6.833539
 7:   Male      Sales 7.845914
 8: Female  Marketing 6.689554
 9:   Male      Sales 7.483933
10: Female      Sales 6.451656

现在我想编写自己的函数来计算整个表或按组计算的平均工作小时数。我想知道下面的功能是否可以进一步简化。更具体地说,如果我在if()未使用时可以避免编写...语句。这是我到目前为止所得到的:

calcMean <- function(data, ...){
  args <- list(...)

  if(length(args) == 0) return(data[, .(`Avg. hours worked` = mean(Hours, na.rm = T))])

  return(data[, .(`Avg. hours worked` = mean(Hours, na.rm = T)), ...])
}

当然,这是一个MWE,我的自定义函数有一个更大的主体,但实质上,相同的概念将适用(如果它可以进一步简化)。

非常感谢任何建议!

0 个答案:

没有答案