iskandarblue
iskandarblue

Reputation: 7526

converting POSIXct back to factor

I have converted a list of times into POSIXct format, and now I need to convert them back to factor, but I am not able to. How can I resolve this ?

> data
[1] "2015-12-01 09:14:24 EST" "2015-12-01 17:51:47 EST" "2015-12-02 08:50:52 EST" "2015-12-02 09:38:45 EST"
[5] "2015-12-06 02:30:46 EST" "2015-12-06 14:02:22 EST"

> as.factor(data)
Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?

Upvotes: 2

Views: 1043

Answers (1)

akrun
akrun

Reputation: 886948

The reason why it didn't work is because the OP have a POSIXlt class object. It is a list and calling factor will result in error

 as.factor(as.POSIXlt(v1))
 #Error in sort.list(y) : 'x' must be atomic for 'sort.list'
 #Have you called 'sort' on a list?

But, if it is POSIXct object, it works

as.factor(as.POSIXct(v1))
#[1] 2015-12-01 09:14:24
#Levels: 2015-12-01 09:14:24

We can convert it to POSIXct and then it should work

as.factor(as.POSIXct(as.POSIXlt(v1)))
#[1] 2015-12-01 09:14:24
#Levels: 2015-12-01 09:14:24

We can check the class by either using class or str

class(as.POSIXct(v1))
#[1] "POSIXct" "POSIXt" 
class(as.POSIXlt(v1))
#[1] "POSIXlt" "POSIXt" 

data

 v1 <- "2015-12-01 09:14:24"

Upvotes: 2

Related Questions