You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R语言中拆分Duration列的小时与分钟并补全缺失值

拆分Duration列为小时和分钟列的解决方案

嗨,我来帮你搞定这个Duration列拆分的问题!针对你给出的数据集,我们可以用正则表达式精准提取小时和分钟,同时自动补全缺失的部分,下面是两种实用的实现方案:

先准备示例数据集

首先我们先把你提供的示例数据集写出来,方便测试代码:

sampledata <- data.frame(
  emp_id = c(1:5),
  Duration = c("10h 50m","5h 34m","9h","4h 15m","23m"),
  stringsAsFactors = FALSE
)

方案一:基础R实现

不用额外的tidyverse包,用基础R结合stringr包就能搞定(如果没装stringr,先运行install.packages("stringr")安装):

library(stringr)

# 提取小时部分,没有小时则补"0h"
sampledata$Hour <- ifelse(
  grepl("\\dh", sampledata$Duration),  # 检查是否存在小时格式
  str_extract(sampledata$Duration, "\\d+h"),  # 提取数字+h的部分
  "0h"  # 缺失时补0h
)

# 提取分钟部分,没有分钟则补"0m"
sampledata$Minute <- ifelse(
  grepl("\\dm", sampledata$Duration),  # 检查是否存在分钟格式
  str_extract(sampledata$Duration, "\\d+m"),  # 提取数字+m的部分
  "0m"  # 缺失时补0m
)

运行后,sampledata的结果如下:

emp_idDurationHourMinute
110h 50m10h50m
25h 34m5h34m
39h9h0m
44h 15m4h15m
523m0h23m

方案二:tidyverse风格实现

如果你习惯用tidyverse的链式操作,这个方案更简洁易读(需要先安装tidyverse:install.packages("tidyverse")):

library(tidyverse)

sampledata_processed <- sampledata %>%
  mutate(
    # 处理小时列
    Hour = case_when(
      str_detect(Duration, "\\dh") ~ str_extract(Duration, "\\d+h"),
      TRUE ~ "0h"
    ),
    # 处理分钟列
    Minute = case_when(
      str_detect(Duration, "\\dm") ~ str_extract(Duration, "\\d+m"),
      TRUE ~ "0m"
    )
  )

处理你的train数据集

如果你要处理从CSV读取的train数据集,只需要把上面代码里的sampledata换成train就行:

train <- read.csv("sampledata.csv", stringsAsFactors = F)

# 用基础R处理train
train$Hour <- ifelse(grepl("\\dh", train$Duration), 
                     str_extract(train$Duration, "\\d+h"), 
                     "0h")

train$Minute <- ifelse(grepl("\\dm", train$Duration), 
                       str_extract(train$Duration, "\\d+m"), 
                       "0m")

小提示

正则表达式\\d+h可以匹配1位或多位数字加h(比如9h、10h都能匹配),\\d+m同理匹配分钟,能覆盖你数据里的所有情况。

内容的提问来源于stack exchange,提问作者prasanth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:38:43