Frage

This is an example of my dataset:

> head(daily[,c(6,7)])->test
> head(test)
                timeMin  min
316 2013-05-02 13:45:00 3239
317 2013-05-03 12:30:00 3260
318 2013-05-04 12:30:00 3165
319 2013-05-05 12:30:00 3404
320 2013-05-06 12:30:00 3514
321 2013-05-07 13:15:00 3626

I need mean(timeMin), in order to know what´s the time of the day (hour:minute) at what the event usually happens. I have tried this:

library(lubridate)
> test$hourMin<-paste(hour(test$timeMin),minute(test$timeMin),sep=":”)
> test$hourMin <- hm(test$hourMin)  

And I got this:

> head(test)
                timeMin  min    hourMin
316 2013-05-02 13:45:00 3239 13H 45M 0S
317 2013-05-03 12:30:00 3260 12H 30M 0S
318 2013-05-04 12:30:00 3165 12H 30M 0S
319 2013-05-05 12:30:00 3404 12H 30M 0S
320 2013-05-06 12:30:00 3514 12H 30M 0S
321 2013-05-07 13:15:00 3626 13H 15M 0S

however, when I try to calculate the mean I had no result:

> mean(test$hourMin)
[1] 0

It should be straightforward, but I don´t know how to do it, since I am a beginner. I would appreciate any help. Thanks

War es hilfreich?

Lösung

It's really not elegant, but the only way I found for now is to change the date components to the same day and to compute the mean on the result. With lubridate :

time <- df$timeMin
time <- update(time, year=2000, month=1, mday=1)
mean(time)
# [1] "2000-01-01 12:50:00 CET"

Hopefully someone will provide something better...

Andere Tipps

I'm calculating seconds past 1st Jan, 2013 midnight and then taking mean of that and adding it back to 1st Jan, 2013 midnight.

I guess there are packages that can do this from just one command but if you, like me, don't wish to rely too much on packages then this solution should work for you.

library(data.table)

timetable <- data.table(TimeMin = c("2013-05-02 13:45:00",
                                    "2013-05-03 12:30:00",
                                    "2013-05-04 12:30:00",
                                    "2013-05-05 12:30:00",
                                    "2013-05-06 12:30:00",
                                    "2013-05-07 13:15:00")
)

timetable <- timetable[, TimePastMin := 
                           difftime(
                               "2013-01-01 00:00:00",
                               TimeMin,
                               units = "secs"
                           )
                       ]

meanTimePastMin <- mean(timetable[, TimePastMin])

meanTimeMin <- strptime("2013-01-01 00:00:00", "%Y-%m-%d %H:%M:%S") - meanTimePastMin

meanTimeMin
# "2013-05-05 00:50:00 IST"
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top