Reputation: 83
If I want to convert a string to POSIXlt there goes something wrong, but I cant figure out what is the problem.
df<-data.frame(a=c("2013-07-01 11:51:03" ,"2013-07-01 12:01:50", "2013-07-01 12:05:13"),b=1:3)
#factor(df[,"a"])
df[,"a"]<-as.POSIXlt(as.character(df[,"a"]),origin = "1960-01-01",tz="GMT")
> Warning message:
In `[<-.data.frame`(`*tmp*`, , "a", value = list(sec = c(3, 50, :
9 variables declared, to replace 1 variablen
df<-data.frame(a=c("2013-07-01 11:51:03" ,"2013-07-01 12:01:50", "2013-07-01 12:05:13"),b=1:3)
df$a<-as.POSIXlt(as.character(df[,"a"]),origin = "1960-01-01",tz="GMT")
factor(df[,"a"])
> Error in sort.list(y) : 'x' should be atomar for 'sort.list'
Till now I use a work around like
a<-as.POSIXlt(as.character(df[,"a"]),origin = "1960-01-01",tz="GMT")
df1<-data.frame(a,df[,"b"])
Upvotes: 3
Views: 1687
Reputation: 59970
POSIXlt
stores everything as a list which is messing you up....
x <- as.POSIXlt(as.character(df[,"a"]),origin = "1960-01-01",tz="GMT")
attributes( x[1] )
$names
[1] "sec" "min" "hour" "mday" "mon" "year" "wday" "yday" "isdst"
$class
[1] "POSIXlt" "POSIXt"
$tzone
[1] "GMT"
# See how the list is of the first element is of length 9? Hence the error:
unlist(x[1])
# sec min hour mday mon year wday yday isdst
# 3 51 11 1 6 113 1 181 0
# POSIXct doesn't do this....
y <- as.POSIXct(as.character(df[,"a"]),origin = "1960-01-01",tz="GMT")
attributes( y[1] )
$class
[1] "POSIXct" "POSIXt"
$tzone
[1] "GMT"
# Stores the date/time as a single element
unlist( y[1] )
#[1] "2013-07-01 11:51:03 GMT"
Upvotes: 3
Reputation: 132706
I recommend using POSIXct:
df[,"a"]<-as.POSIXct(as.character(df[,"a"]),tz="GMT")
If you have to use POSIXlt (why?):
df$a <- as.POSIXlt(as.character(df[,"a"]),tz="GMT")
The problem is that objects of class POSIXlt
are actually lists. $<-
can deal with that correctly, [<-
cannot.
Upvotes: 5