【问题标题】:Converting time from text to numbers R将时间从文本转换为数字 R
【发布时间】:2021-06-16 09:59:39
【问题描述】:

我有一份调查问卷,我想估算受访者提交的时间。我收到以下 responsetime 变量格式的数据:

mydata <- tibble(
id = c(1:10),
responsetime = c("24 minutes 4 seconds", "1 hour 2 minutes 55 seconds", "15 minutes 5 seconds", 
                 "2 hours 45 minutes 4 seconds", "55 minutes 23 seconds", "5 minutes 55 seconds", 
                 "10 minutes 34 seconds", "27 minutes 11 seconds", "1 hour 6 minutes 57 seconds", 
                  "45 minutes 45 seconds")
)

我想估计响应时间变量的平均时间,但在将文本转换为整数时遇到了麻烦。

【问题讨论】:

    标签: r tidyverse lubridate


    【解决方案1】:

    你可以转换成lubridate::period对象

    library(lubridate)
    period(mydata$responsetime)
    
     #[1] "24M 4S"    "1H 2M 55S" "15M 5S"    "2H 45M 4S" "55M 23S"   "5M 55S"   
     #[7] "10M 34S"   "27M 11S"   "1H 6M 57S" "45M 45S" 
    

    要以分钟为单位获得平均响应时间,您可以这样做 -

    mean(period_to_seconds(period(mydata$responsetime)))/60
    #[1] 47.88833
    

    【讨论】:

    • 完美运行。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    相关资源
    最近更新 更多