首页 > 解决方案 > 将 week+day(39+3) 变量更改为 R 中的周或天

问题描述

我正在使用一个以周数+天数(39+3)为单位的妊娠长度 [因子] 变量,我需要能够使用一个整数,我可以在组之间进行比较并计算平均值。所以要么 276 天 (37*7+3) 要么 37,43 周 (37+(3/7))。有什么建议吗?

标签: r

解决方案


一些摆弄data.table..

样本数据

library( data.table )
set.seed(123)
DT <- data.table( pregnancy.length = paste0( sample(20:42, 100, replace = TRUE), 
                                             "+",
                                             sample(1:6, 100, replace = TRUE) ), 
                  stringsAsFactors = FALSE )

代码

#first, split the pregnancy-length on the `+`-sign  
DT[, c("weeks", "days") := lapply( tstrsplit( pregnancy.length, "\\+"), as.numeric )]
#then caluculate weeks, days, or both
DT[, `:=`( week.total = weeks + days / 7, day.total = weeks * 7 + days )]

**输出

head(DT)
#    pregnancy.length weeks days week.total day.total
# 1:             26+4    26    4   26.57143       186
# 2:             38+2    38    2   38.28571       268
# 3:             29+3    29    3   29.42857       206
# 4:             40+6    40    6   40.85714       286
# 5:             41+3    41    3   41.42857       290
# 6:             21+6    21    6   21.85714       153

推荐阅读