【问题标题】:R Convert char to timeR 将字符转换为时间
【发布时间】:2021-02-01 01:42:25
【问题描述】:

我有一列军事时间值,df1$appt_times,格式为“13:30”,全部为 5 个字符,“00:00”。我已经尝试过 POSIXct,但它在值中添加了今天的日期。我也尝试过 lubridate,但无法让它发挥作用。最近我正在尝试使用 chron 并且到目前为止也没有成功

目标是,一旦完成,我会将时间分组为因子级别,目前我无法对它们执行任何条件操作,除非我也错了;)

> df1$Time <-  chron(times = df1$appt_time)
Error in convert.times(times., fmt) : format h:m:s may be incorrect
In addition: Warning message:
In unpaste(times, sep = fmt$sep, fnames = fmt$periods, nfields = 3) :
  106057 entries set to NA due to wrong number of fields

还有df1$Time &lt;- chron(times(df1$appt_time))和上面一样的错误

以及使用格式明确的不同尝试:

> df1$appt_time <- chron(df1$appt_time, format = "h:m")
Error in widths[, fmt$periods, drop = FALSE] : subscript out of bounds

如果有人能指出我的错误或提出更好的方法来完成这项任务,我将不胜感激。

【问题讨论】:

  • 检查日期格式在 R 中的工作方式:stat.berkeley.edu/~s133/dates.html
  • @Turksarama - 不幸的是,您的链接没有任何用处。如果您有任何关于如何将条件逻辑应用于时间值的信息,请告诉我

标签: r time chron


【解决方案1】:

您可以使用as.POSIXct

df1$date_time <- as.POSIXct(df1$appt_time, format = '%H:%M', tz = 'UTC')

由于您没有日期,因此将根据appt_time 分配今天的日期和时间。

例如-

as.POSIXct('13:30', format = '%H:%M', tz = 'UTC')
#[1] "2021-02-01 13:30:00 UTC"

【讨论】:

    【解决方案2】:

    如果您需要在分组之前对时间进行算术运算,解决此问题的一种方法是将分钟视为小时的一小部分:

    # If you need to do some extra arithmetic prior to coercing to factor: 
    as.numeric(substr(test1, 1, 2)) + (as.numeric(substr(test1,  4, 5))/60)
    
    # Otherwise: 
    as.factor(test1)
    

    其中 df1$appt_times == test1

    test1 <- c('13:30','13:45', '14:00', '14:15', '14:30', '14:45', '15:00')
    

    【讨论】:

      【解决方案3】:

      无法以我认为我想出这个 DIIIIIRRRRRRRRRRRTY 解决方案的方式找到与时间一起工作的解决方案。

      #converted appt_time to POSIXct format, which added toady's date 
      df9$appt_time <- as.POSIXct(df9$appt_time, format = '%H:%M')
      
      #Since I am only interesting in creating a value based on if the time falls within a specific range I decided I could output this new value, 'unclassed', to a column and then manually eyeball the values I needed that corresponded to my ranges
      df9$convert <- unclass(df9$appt_time)
      
      #Using the, manually obtained, unclassed values I was able create the factor levels I wanted
      group_appt_time <- function(convert){
        ifelse (convert >= 1612624500 & convert <= 1612637100, 'Morning',
                        ifelse (convert >= 1612638000 & convert <= 1612647900, 'Mid-Day',
                                ifelse (convert >= 1612648800 & convert <= 1612658700, 'Afternoon',
                                        'Invalid Time')))
      }
      
      df9$appt_time_grouped <- as.factor(group_appt_time(df9$convert))
      

      这是一个研究项目,我不需要以持续的方式重新创建它才能正常工作

      【讨论】:

        猜你喜欢
        • 2015-07-22
        • 1970-01-01
        • 1970-01-01
        • 2015-05-20
        • 1970-01-01
        • 1970-01-01
        • 2016-09-04
        • 2023-03-15
        相关资源
        最近更新 更多