ilyas
ilyas

Reputation: 629

Convert sequential numeric data into time format in R

Let's say I have a dataframe with a column t which consists of cumulative time differences of seconds from the first point of the dataset with a frequency of 10 Hz. How can I convert this into R time in Min:Second format, so that it will show up in ggplots. I will only show every 5 minutes a tick on the x axis, and the corrsponding time in 00:00, 05:00, 10:00...etc.

Example:

# t columns is in seconds, thus 2000 seconds makes 33.33 minutes
# Last tick value on the x axis I will show is 30:00
d1 = 10 + runif(n = 5000)
d2 = 20 + runif(n = 5000)
d3 = 30 + runif(n = 5000)
d4 = 40 + runif(n = 5001)
d = c(d1,d2,d3,d4)
t = seq(0, 2000, by = 0.1)
DF = data.frame(t = t, d = d)
ggplot(data = DF, aes(x = t, y = d)) + geom_line()

Thank you,

Upvotes: 1

Views: 282

Answers (2)

cuttlefish44
cuttlefish44

Reputation: 6796

I think it would be better to convert values to POSIXct class with dummy-date via difftime.

DF$min_sec <- as.POSIXct("2016-01-01") + as.difftime(DF$t, unit="secs")

ggplot(DF, aes(x = min_sec, y = d)) + geom_point() + 
  scale_x_datetime(date_breaks = "5 min", date_labels = "%M:%S", minor_breaks=NULL)

enter image description here

Upvotes: 1

Sean Reddy
Sean Reddy

Reputation: 149

DF = data.frame(t = seq(0, 2000, by = 0.1), data = runif(n = 20001))

DF$t <- lubridate::ms(DF$t)

For the second part you might want to check out this question/answer (including comments) from a few hours ago. He asked the exact same question.

R: Aggregating time series data returns NA

I aggregated his data every 5 minutes like this:

library(xts)
    mydata    <- read.csv("data.csv")
    times     <- mydata$Time
    X         <- as.POSIXct(times)
    X         <- as.xts(X)
    period.apply(mydata$T1, INDEX = endpoints(X, "minutes", 5), function(x) mean(x, na.rm=T))

then he said he was plotting it like this:

DataTable <- table(cut(data, breaks="5 mins"))

Upvotes: 0

Related Questions