[R] Change data frame to time series data
Enrico Schumann
e@ @end|ng |rom enr|co@chum@nn@net
Wed Oct 2 09:01:58 CEST 2024
On Wed, 02 Oct 2024, roslinazairimah zakaria writes:
> Dear all, I have a data in data frame and would like to change to time
> series data. Thank you for any help given.
>
>> str(dt)'data.frame': 525600 obs. of 3 variables:
> $ time : chr "2014-01-01 00:00:00" "2014-01-01 00:01:00"
> "2014-01-01 00:02:00" "2014-01-01 00:03:00" ...
> $ cnt_charge_events: int 0 0 0 0 0 0 0 0 0 0 ...
> $ count : int 0 0 0 0 0 0 0 0 0 0 ...
>
>> head(dt) time cnt_charge_events count
> 1 2014-01-01 00:00:00 0 0
> 2 2014-01-01 00:01:00 0 0
> 3 2014-01-01 00:02:00 0 0
> 4 2014-01-01 00:03:00 0 0
> 5 2014-01-01 00:04:00 0 0
> 6 2014-01-01 00:05:00 0 0
>
>
>> dt_ts <- xts(dt$count, dt$time)Error in xts(dt$count, dt$time) :
> order.by requires an appropriate time-based object> head(dt_ts)Time Series:
> Start = 1
> End = 6
> Frequency = 1
> dt_ts.date dt_ts.time dt[, 3]
> 1 16071 1 0
> 2 16071 2 0
> 3 16071 3 0
> 4 16071 4 0
> 5 16071 5 0
> 6 16071 6 0Dear
Your "time" column consists of character strings, not
actual timestamps.
dt <- read.table(
text ="
time, cnt_charge_events, count
2014-01-01 00:00:00, 1, 1
2014-01-01 00:01:00, 2, 2
2014-01-01 00:02:00, 3, 3
2014-01-01 00:03:00, 4, 4
2014-01-01 00:04:00, 5, 5
2014-01-01 00:05:00, 6, 6",
header = TRUE, sep = ",")
library("xts")
xts(dt$count, dt$time) ## won't work
## Error in xts(dt$count, dt$time) :
## order.by requires an appropriate time-based object
dt$time <- as.POSIXct(dt$time)
xts(dt$count, dt$time)
## [,1]
## 2014-01-01 00:00:00 1
## 2014-01-01 00:01:00 2
## 2014-01-01 00:02:00 3
But be sure to read about ?as.POSIXct; in particular,
the handling of timezones/daylight-saving time.
> [[alternative HTML version deleted]]
Please send plain-text messages to this list; otherwise,
the results become hard to read.
--
Enrico Schumann
Lucerne, Switzerland
https://enricoschumann.net
More information about the R-help
mailing list