Domanda

Sto leggendo una tabella e contiene stringhe che descrivono i timestamp. Voglio solo convertire da stringa a un tipo datetime incorporato ...

R> Q <- read.table(textConnection('
               tsstring
1 "2009-09-30 10:00:00"
2 "2009-09-30 10:15:00"
3 "2009-09-30 10:35:00"
4 "2009-09-30 10:45:00"
5 "2009-09-30 11:00:00"
'), as.is=TRUE, header=TRUE)
R> ts <- strptime(Q$tsstring, "%Y-%m-%d %H:%M:%S", tz="UTC")

se provo a memorizzare la colonna datetime in data.frame, ottengo un errore curioso:

R> Q$ts <- ts
Error in `$<-.data.frame`(`*tmp*`, "ts", value = list(sec = c(0, 0, 0,  : 
  replacement has 9 rows, data has 5

ma se passo attraverso una rappresentazione numerica contenuta in data.frame, funziona ...

R> EPOCH <- strptime("1970-01-01 00:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC")
R> Q$minutes <- as.numeric(difftime(ts, EPOCH, tz="UTC"), units="mins")
R> Q$ts <- EPOCH + 60*Q$minutes

qualche aiuto per capire la situazione?

È stato utile?

Soluzione

strptime restituisce la classe POSIXlt, è necessario POSIXct nel frame di dati:

R> class(strptime("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
[1] "POSIXt"  "POSIXlt"
R> class(as.POSIXct("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
[1] "POSIXt"  "POSIXct"

La classe <=> rappresenta il numero (firmato) di secondi dall'inizio di 1970 come vettore numerico. La classe <=> è un elenco denominato di vettori che rappresentano sec, min, ora, mday, mon, year, ecc.

R> unclass(strptime("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
$sec
[1] 0
$min
[1] 0
$hour
[1] 10
$mday
[1] 30
$mon
[1] 8
$year
[1] 109
$wday
[1] 3
$yday
[1] 272
$isdst
[1] 0
attr(,"tzone")
[1] "UTC"

R> unclass(as.POSIXct("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
[1] 1.254e+09
attr(,"tzone")
[1] "UTC"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top