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

R语言中带字符标识的时间向量转秒数的问题求助

解决时间字符串转秒数的问题

问题描述

现有时间向量:

time = c("2m 14,8s", "1h 47m 46,9s", "34,7s")

需要转换为以秒为单位的数值向量:

time = c(134.8, 6466.9, 34.7)

原尝试代码报错non-numeric argument to binary operator,且不清楚如何对转换结果求和。

错误原因分析

原代码里,ifelse会对分割后的所有元素执行判断和转换,未匹配到h/m的元素会被处理成非数值类型,触发乘法运算的类型错误;同时lapply返回的是列表结构,无法直接进行求和操作。

解决方案

方法1:基础R实现

先统一替换逗号为点(适配R的小数格式),再逐个解析时间片段计算总秒数:

# 替换逗号为点
time_clean = sub(",", ".", time)

# 定义转换函数
convert_to_seconds = function(t_str) {
  parts = strsplit(t_str, " ")[[1]]
  total = 0
  for(part in parts) {
    num = as.numeric(sub("[a-z]", "", part))
    if(grepl("h", part)) {
      total = total + num * 3600
    } else if(grepl("m", part)) {
      total = total + num * 60
    } else if(grepl("s", part)) {
      total = total + num
    }
  }
  return(total)
}

# 应用函数得到结果
time_seconds = sapply(time_clean, convert_to_seconds)
# 去掉命名,转为纯数值向量
time_seconds = unname(time_seconds)

运行结果:

> time_seconds
[1]  134.8 6466.9   34.7

方法2:使用lubridate包(更简洁)

利用lubridate的周期解析能力快速转换:

library(lubridate)

# 替换逗号为点后解析为周期对象,再转成秒数
time_seconds = as.numeric(period(sub(",", ".", time)), "seconds")

运行结果与方法1一致。

求和转换结果

直接对转换后的数值向量调用sum()即可:

sum(time_seconds)
# 输出:6636.4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:10:56