Convert R time column to specific rows

I have a column representing the time in a data frame in R.

when I call the str () function on a column, it says something like this

>str(df2$Time)
 Factor w/ 1441 levels "","00:01","00:02","00:03",..: 1086 1096 1111 and so on

I want to convert this column to a row type so that if the time is less than 12:00, it should be changed to the string "moring", if the time is between 12:00 and 6:00 it is "daylight", etc.

As a first step, I decided to convert this vector to the time type of the data frame column, so I used the chron function.

I typed the following command:

>df2$Time<-chron(times=df2$Time,format=c('h:m'))
 Error in convert.times(times., fmt) : format h:m may be incorrect
 In addition: Warning message:
In is.na(out$s) : is.na() applied to non-(list or vector) of type 'NULL"

so I figured I should add a second parameter in the format, so I tried the following:

df2$Time<-chron(time=df2$Time,format=c('h:m:s'))

But still there was the same mistake

, , , . - , , , ..

.

+4
3

chron "times" cut:

library(chron)

# data in reproducible form
df2 <- data.frame(Times = c("00:01","12:02","19:03"))

df2$Times <- times(paste0(df2$Times, ":00")) # append a chron "times" class column
breaks <- c(0, 12, 18, 24) / 24 # times are internally fractions of a day
labels <- c("morning", "daylight", "evening")
df2$ind <- cut(df2$Times, breaks, labels, include.lowest = TRUE)

:

> df2
     Times      ind
1 00:01:00  morning
2 12:02:00 daylight
3 19:03:00  evening

.

.

+4

lubridate ( Joran, ) hour hm:

Time <- hour(hm("13:24","19:32","3:45","08:25", "21:45", "11:13", "00:00"))
your_breaks <- hour(hm("00:00", "6:00", "12:00", "18:00", "23:59"))
your_labels <- c("Night", "Morning", "Afternoon", "Evening")
cut(x=Time, breaks=your_breaks, labels=your_labels, include.lowest=TRUE)

[1] Afternoon Evening   Night     Morning   Evening   Morning   Night
+4

:

time <- expand.grid(0:23,0:59)
time <- apply(time,1,function(x)sprintf("%02i:%02i",x[1],x[2]))

- , POSIXct, cut :

time <- strptime(paste("01/01/01",time),"%y/%m/%d %H:%M")

cut(time,
    breaks= as.POSIXct(paste("2001-01-01",
                       c("00:00:00", "12:00:00", "18:00:00", "23:59:59"))),
    labels=c('morning','afternoon','night'))
+1

Source: https://habr.com/ru/post/1527450/


All Articles