Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using date time objects in a data frame

Tags:

datetime

r

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"])
like image 336
Heiko Avatar asked May 29 '26 10:05

Heiko


2 Answers

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.

like image 78
Roland Avatar answered Jun 01 '26 01:06

Roland


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"
like image 23
Simon O'Hanlon Avatar answered Jun 01 '26 02:06

Simon O'Hanlon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!