首页 > 解决方案 > 如何使用 R 将用文字 (Xhours Xminutes) 写成的持续时间转换为数字?

问题描述

我正在使用将时间写成文字的数据......

time <- c('1 hour 1 minute', '2 hours 3 minutes', '45 minutes')

我想将这些时间转换为以下格式...

time <- c(61,123,45)

我想知道是否有人有使用 r 的简单方法?

标签: rtime

解决方案


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建议的使用)


推荐阅读