r - 将 week+day(39+3) 变量更改为 R 中的周或天
问题描述
我正在使用一个以周数+天数(39+3)为单位的妊娠长度 [因子] 变量,我需要能够使用一个整数,我可以在组之间进行比较并计算平均值。所以要么 276 天 (37*7+3) 要么 37,43 周 (37+(3/7))。有什么建议吗?
解决方案
一些摆弄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
推荐阅读
- javascript - ng-click 没有触发
- hibernate - 使用 hibernate join.fetch 减少数据库调用
- sqlite - sqlite3.ProgrammingError:您没有为绑定 8 提供值
- bazel - 列出目录中的所有 bazel 目标
- flutter - 尝试在颤振中通过 ffmpeg 插件发送我的 RTSP IP 摄像机流
- javascript - 在 html 中使用 react 时如何使用 npm 包?
- javascript - 删除 MongoDB 集合中的特定对象
- node.js - Simple multiplexing node.js stream - chunk concatenated issue
- wix - 通过 wix burn 在启动时自动更新应用程序
- c# - 如果 Azure 队列中的消息处理引发异常,则获取状态