如何将MM::SS字符串转换为时间格式,然后对其进行操作
How to convert MM::SS string to time format and then manipulate it
我有以下数据框:
library(tibble)
dat <- structure(list(title = c("Title A", "Title B", "Title C"), tm = c(
"31:17",
"30:28", "32:06"
)), row.names = c(NA, -3L), spec = structure(list(
cols = list(title = structure(list(), class = c(
"collector_character",
"collector"
)), tm = structure(list(), class = c(
"collector_character",
"collector"
))), default = structure(list(), class = c(
"collector_guess",
"collector"
)), delim = ","
), class = "col_spec"), class = c(
"spec_tbl_df",
"tbl_df", "tbl", "data.frame"
))
看起来像这样:
> dat
# A tibble: 3 × 2
title tm
<chr> <chr>
1 Title A 31:17
2 Title B 30:28
3 Title C 32:06
第二列是时间,但是是字符。我想做的是
每行增加 5 分钟;结果:
Title A 36:17
Title B 35:28
Title C 37:06
策略是先将tm
转换成数值形式。但是我这一步失败了
dat %>%
mutate(nt = hms::as_hms(as.numeric(tm) + 5))
它给了我:
title tm nt
<chr> <chr> <time>
1 Title A 31:17 NA
2 Title B 30:28 NA
3 Title C 32:06 NA
正确的做法是什么?
使用lubridate
-
library(dplyr)
library(lubridate)
dat %>%
mutate(tm = ms(tm) + minutes(5),
tm_string = sprintf('%02d:%02d', tm@minute, tm@.Data))
# title tm tm_string
# <chr> <Period> <chr>
#1 Title A 36M 17S 36:17
#2 Title B 35M 28S 35:28
#3 Title C 37M 6S 37:06
我有以下数据框:
library(tibble)
dat <- structure(list(title = c("Title A", "Title B", "Title C"), tm = c(
"31:17",
"30:28", "32:06"
)), row.names = c(NA, -3L), spec = structure(list(
cols = list(title = structure(list(), class = c(
"collector_character",
"collector"
)), tm = structure(list(), class = c(
"collector_character",
"collector"
))), default = structure(list(), class = c(
"collector_guess",
"collector"
)), delim = ","
), class = "col_spec"), class = c(
"spec_tbl_df",
"tbl_df", "tbl", "data.frame"
))
看起来像这样:
> dat
# A tibble: 3 × 2
title tm
<chr> <chr>
1 Title A 31:17
2 Title B 30:28
3 Title C 32:06
第二列是时间,但是是字符。我想做的是 每行增加 5 分钟;结果:
Title A 36:17
Title B 35:28
Title C 37:06
策略是先将tm
转换成数值形式。但是我这一步失败了
dat %>%
mutate(nt = hms::as_hms(as.numeric(tm) + 5))
它给了我:
title tm nt
<chr> <chr> <time>
1 Title A 31:17 NA
2 Title B 30:28 NA
3 Title C 32:06 NA
正确的做法是什么?
使用lubridate
-
library(dplyr)
library(lubridate)
dat %>%
mutate(tm = ms(tm) + minutes(5),
tm_string = sprintf('%02d:%02d', tm@minute, tm@.Data))
# title tm tm_string
# <chr> <Period> <chr>
#1 Title A 36M 17S 36:17
#2 Title B 35M 28S 35:28
#3 Title C 37M 6S 37:06