Shery - 1 year ago 76
R Question

# Calculate Avg Time in R

My

`Dataframe`
called
`copy1`
:

``````    copy1
Source: local data frame [4 x 4]
Groups: GM [2]

(fctr)         (fctr)         (fctr)                  (int)
1   ED          13:15          16:16                    181
2   ED          16:12          17:44                     92
3   LD          15:32          17:27                    115
4   LD          14:38          17:11                    153
``````

I want to calculate
`Avg.Close.Time`
Per
`GM`

I have tried:

``````copy1\$Avg.Start.Time <-strptime(copy1\$Avg.Start.Time, "%H:%M")
copy1%>%group_by(GM)%>%
summarise(mean(copy1\$Avg.Start.Time,na.rm=T))
``````

But get this:

``````Error: column 'Avg.Start.Time' has unsupported type : POSIXlt, POSIXt
``````

I have also tried using
`lubridate`
:

``````copy1\$Avg.Start.Time <- hm(copy1\$Avg.Start.Time)

mean(copy1\$Avg.Start.Time,na.rm = T)
``````

But get "0"

Any ideas how can I calculate
`Avg.Start.Time`
Per
`GM`
?

You need to first convert the column to time format by,

``````copy1\$Avg.Start.Time <- as.POSIXct(copy1\$Avg.Start.Time, format = "%H:%M")
``````

You can then use `aggregate` from base R to get `mean` for every `GM`

``````aggregate(Avg.Start.Time~GM, copy1, mean)

#  GM      Avg.Start.Time
#1 ED 2016-08-24 14:43:30
#2 LD 2016-08-24 15:05:00
``````

If you want it in `HH:MM` format you can wrap it up inside `format`

``````aggregate(Avg.Start.Time~GM, copy1, function(x) format(mean(x),format = "%H:%M"))

#  GM Avg.Start.Time
#1 ED          14:43
#2 LD          15:05
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download