apps92 apps92 - 5 months ago 32
R Question

Converting R time column to specific strings

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

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

Factor w/ 1441 levels "","00:01","00:02","00:03",..: 1086 1096 1111 and so on

The thing is I want to conver this column into string type such that if the time is less than 12:00, it should get modified to the string "moring" , if time is between 12:00 and 6:00 , it is "daylight" and so on.

The first step I thought was to convert this vector to time type of column of data frame, so I used chron function.

I typed the following command,

Error in convert.times(times., fmt) : format h:m may be incorrect
In addition: Warning message:
In$s) : applied to non-(list or vector) of type 'NULL"

so I guessed I should have added second parameter in format so I tried the following :


But still got the same error

I know this is just the first step, may be my approach too is wrong. Can anyone suggest me how to convert these time data cells to morning, evening , night etc.

Any help is much appreciated.


Use chron's "times" class and cut:


# 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)

which gives:

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

Next time please supply your data in reproducible form.

REVISED Minor simplification and fixed typo.