首页 > 解决方案 > 从 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

标签: r

解决方案


我会说不是最好的答案,但一种方法是

#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

推荐阅读