【问题标题】:How to convert a character to a numeric [duplicate]如何将字符转换为数字[重复]
【发布时间】:2021-08-11 11:52:36
【问题描述】:

在我的数据集中的特定单元格下方:

PT23M55.39S

单元格告诉我用户在网页上花费了多少分钟(23 分钟)和多少秒(55.39 秒)。

单元格的属性为 char(字符)。

如何将其转换为仅以秒(23 * 60 + 55.39 = 1435.39 秒)表示访问时间的数字?

【问题讨论】:

    标签: r


    【解决方案1】:

    使用lubridate 函数msperiod_to_seconds 你可以做到-

    library(lubridate)
    
    x <- 'PT23M55.39S'
    period_to_seconds(ms(x))
    #[1] 1435.39
    

    在 base R 中,您可以使用strcapture 将使用正则表达式的数据分别提取为分钟和秒,将minutes 的值乘以 60 并将两个数字相加。

    strcapture('[A-Z]+(\\d+)M(\\d+\\.\\d+)', x, 
               proto = list(minutes = numeric(), seconds = numeric())) |>
      transform(duration_in_seconds = minutes * 60 + seconds)
    

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 2016-09-06
      • 2014-11-15
      • 2012-07-24
      • 1970-01-01
      • 2018-10-04
      相关资源
      最近更新 更多