0

我有一列军事时间值,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 <- 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

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

4

3 回答 3

2

您可以使用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"
于 2021-02-01T02:10:48.467 回答
0

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

# 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')
于 2021-02-01T02:12:56.047 回答
0

无法以我认为我想出这个 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))

这是一个研究项目,不是我需要以持续的方式重新创建的东西,所以它可以工作

于 2021-02-06T22:13:10.030 回答