【问题标题】:recode a time variable (format: hh:mm:ss) into a categorical variable将时间变量(格式:hh:mm:ss)重新编码为分类变量
【发布时间】:2022-11-14 19:46:54
【问题描述】:

我有一个名为“duration.video”的变量,格式如下:hh:mm:ss,我想将其重新编码为分类变量('少于 5 分钟,5 到 30 分钟等)

这是我的代码行: video$Duration.video<-as.factor(car::recode(video$Duration.video, "00:00:01:00:04:59='不到 5 分钟';00:05:00:00: 30:00='5 到 30 分钟之间';00:30:01:01:59:59='超过 30 分钟和不到 2h';02:00:00:08:00:00='2h 和更多的'”))

该代码不起作用,因为变量的所有模式都放在一个类别中(“5 到 30 分钟之间”)。

我认为这是因为我的变量是字符格式,但我无法将其转换为数字。而且也许带有“:”的格式对于 R 中的重新编码可能是一个问题。有人可以帮我吗?

我尝试使用 Itime 进行转换,但结果保持不变。

【问题讨论】:

标签: r time format numeric recode


【解决方案1】:

这是一个整洁的解决方案。您可以使用 base R 完成此操作,但这可能更容易。

library(lubridate)
library(dplyr)

df <- data.frame(
  duration_string = c("00:00:03","00:00:06","00:12:00","00:31:00","01:12:01")
  )

df <- df %>%
  mutate(
    duration = as.duration(hms(duration_string)),
    cat_duration = case_when(
      duration < dseconds(5) ~ "less than 5 secs",
      duration >= dseconds(5) & duration < dminutes(30) ~ "between 5 secs and 30 mins",
      duration >= dminutes(30) & duration < dhours(1) ~ "between 30 mins and 1 hour",
      duration > dhours(1) ~ "more than 1 hour",
    ) ,
      cat_duration = factor(cat_duration,levels = c("less than 5 secs",
                                                    "between 5 secs and 30 mins",
                                                    "between 30 mins and 1 hour",
                                                    "more than 1 hour"
                                                    ))
  ) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多