r - 如何将 MM::SS 字符串转换为时间格式,然后对其进行操作
问题描述
我有以下数据框:
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
推荐阅读
- c# - 即使gridview为空也显示gridview的页眉和页脚并且在空gridview中不显示任何记录消息
- cadence-workflow - Cadence Service 是否提供任何健康检查 API 端点
- rust - 是否有一种方法可以使 Err 上的函数短路,例如 SQL 的 ifnull 或 coalesce?
- java - 如何从 firebase 实时数据库中获取数据并将其显示在微调器上
- spring - 更新到最新版本后替换 @EnableSwagger2
- java - 如何让 JFrame 在 10 秒后自行关闭?
- javascript - PHP 和 JS 以不同的方式转换相同的日期
- python - 如何在python中找到最接近角落的图像中的哪个坐标?
- java - 如何使用 docker & IntelliJ 作为文本编辑器在本地部署 Java webapp?
- react-native - 有没有办法在 React Native 中连接到一个简单的 TCP 套接字?