r - 如何使用 R 将用文字 (Xhours Xminutes) 写成的持续时间转换为数字?
问题描述
我正在使用将时间写成文字的数据......
time <- c('1 hour 1 minute', '2 hours 3 minutes', '45 minutes')
我想将这些时间转换为以下格式...
time <- c(61,123,45)
我想知道是否有人有使用 r 的简单方法?
解决方案
hours <- stringr::str_extract_all(time, "[0-9]+(?=\\s*hour)")
hours <- replace(hours, sapply(hours, Negate(length)), "0")
hours <- as.integer(unlist(hours))
hours
# [1] 1 2 0
minutes <- stringr::str_extract_all(time, "[0-9]+(?=\\s*minute)")
minutes <- replace(minutes, sapply(minutes, Negate(length)), "0")
minutes <- as.integer(unlist(minutes))
minutes
# [1] 1 3 45
hours*60 + minutes
# [1] 61 123 45
或者更紧凑一点:
mtx <- cbind(
stringr::str_extract_all(time, "[0-9]+(?=\\s*hour)", TRUE),
stringr::str_extract_all(time, "[0-9]+(?=\\s*minute)", TRUE))
storage.mode(mtx) <- "numeric"
mtx[is.na(mtx)] <- 0
mtx
# [,1] [,2]
# [1,] 1 1
# [2,] 2 3
# [3,] 0 45
60 * mtx[,1] + mtx[,2]
# [1] 61 123 45
### or
mtx %*% c(60, 1)
# [,1]
# [1,] 61
# [2,] 123
# [3,] 45
(https://stackoverflow.com/a/20791975storage.mode
建议的使用)
推荐阅读
- postgresql - 无法将 hstore 扩展安装到新创建的架构
- python - 运行码机/深度学习出错
- scala - 从 Excel 文件中读取日期值
- python - 迭代分组数据框中的组
- android - 需要 4-5 秒才能看到带有大 ArrayList 数据的可见视图到 NestedScrollView 内的 RecyclerView
- oracle - 如何在 oracle 查询中获取字符串的第一行?
- python-3.x - python setuptools依赖于绝对路径
- windows - 远程位置的文件访问检查
- android - 在 Android 中从 alpha、red、green、blue 创建颜色 int
- windows - 无法拉取 nanoserver:1903 Docker 映像