舍入 datediffs 的平均值

问题描述 投票:0回答:1

在我的 R data.table 中,我使用减法(简单的数学表达式)计算了日期的差异。我的差异以天数表示。然后我取跨组的 datediffs 的平均值。平均值也以天数表示,但我不知道如何舍入结果。这看起来很简单,任何人都可以在 base R 或 data.table 中提供答案吗?我对 R 比较陌生。

请注意,我正在避免使用 dplyr,因为我试图将所有内容都保留在 data.table 语言中。

假设 days_elapsed 是感兴趣的日期差异。请注意,class(days_elapsed) = datediff。在 R studio days_elapsed 中显示为“325 天”。 days_elapsed 两组的平均值显示为类似“178.29423 天”的内容。我希望“days_elapsed”的平均值以整日(“178 天”)表示。

我在一组两列的days_elapsed(days_elapsed1,days_elapsed2)上尝试了以下两种方法。我没有为这个问题提供可重现的例子。如果没有它,我希望我的解释足够清楚。请注意我的代码有时会使用蛮力,因为我是 R 的新手。

# (a) Applying rounding at the point of calculating the date difference:  
dt_summ1 <- mydt[, .(days_elapsed1 =
                   if(grp==1) 
                   {round(fixed_date - date_a, 0)}
                   else {round(date_a - fixed_date, 0)}
               days_elapsed2 = 
                   if(grp==1) 
                     {round(fixed_date - date_a, 0)}
                   else {round(date_a - fixed_date, 0)}
dt_summ1_collapsed <- dt_summ1[, .SD[1], by=.(id, grp)] 
subset <- names(dt_summ1_collapse)[3:6]
dt_summ_collapsed2 <- dt_summ1_collapsed[, lapply(.SD, mean, na.rm=TRUE), 
                   by=exp_period, .SDcols=subset]

# (I only make copies of the data.tables in order to debug this code.)

#(b) Using the round_date function on days_elapsed after the mean was calculated:
n_days <-c("days_elapsed1", "days_elapsed2")
dt_summ_collapsed2[, (n_days):=round_date(.SD,unit=day), .SDcols=n_days]

Error in as.character(unit) : 
  cannot coerce type 'closure' to vector of type 'character'
r data.table rounding datediff
1个回答
0
投票

函数

round_date()
期望输入是日期/日期差异。但是,
days_elapsed1
days_elapsed2
的列是数值。

如果您将最后一行替换为以下内容,它应该可以工作:

dt_summ_collapsed2[, (n_days):=round(.SD), .SDcols=n_days]
© www.soinside.com 2019 - 2024. All rights reserved.