r - 从 R 中的持续时间列中拆分小时和分钟
问题描述
在我的数据集中有一个名为持续时间的列。从中我想将小时和分钟分成 2 个单独的列。如果没有小时或分钟,则要相应地添加 0h 或 0m。
在下图中提供了相同的现有列详细信息以及预期的新列:
train <- read.csv("sampledata.csv", stringsAsFactors = F)
train$Duration
编辑:
sampledata <- data.frame(
emp_id = c (1:5),
Duration = c("10h 50m","5h 34m","9h","4h 15m","23m"),
stringsAsFactors = FALSE
)
sampledata$Duration
解决方案
我会说不是最好的答案,但一种方法是
#Get numbers next to hours and minutes
hour_minute <- sub("(\\d+)h (\\d+)m", "\\1-\\2", sampledata$Duration)
sampledata[c("hour", "minutes")] <- t(sapply(strsplit(hour_minute, "-"),
function(x) {
if (length(x) == 2) x
else if (endsWith(x, "h")) c(sub("h", "", x), 0)
else c(0, sub("m", "", x))
}))
sampledata
emp_id Duration hour minutes
1 1 10h 50m 10 50
2 2 5h 34m 5 34
3 3 9h 9 0
4 4 4h 15m 4 15
5 5 23m 0 23
推荐阅读
- android - 如何在android中保存短信
- continuous-deployment - 基础架构即代码 (IaC) 是针对软件基础架构、虚拟硬件基础架构还是两者兼而有之?
- php - 在 Woocommerce 中使用自定义选择字段触发 update_checkout
- php - 如何使用 Guzzle 进行分页
- html - 如何使用 Nginx 传递没有扩展名的文件?
- c# - 在 VSTS CI/CD 中构建 Hive 项目时出错
- javascript - 从对象创建一个网格数组(THREE.JS 和 GLTF)
- scala - 如何在 Scala 中从 List[Array[String]] 中获取集合
- c# - Swashbuckle MapType
不适用于参数 - python - 聚类成三个最近的邻居