Question

Hello I want calculate the mean of a variable hhmmss that have NA values.

     X1500m
1   0:04:13
2   0:04:06
3   0:03:50
4   0:03:42
5   NA
6   NA
7   NA
8   0:03:59
9   NA
10  NA
11  NA
12  0:03:50

If I hadn't have NA values I could calculate the mean using library(chron) and this commandtimes(mean(as.numeric(times(X1500m)))).

I use times(mean(as.numeric(times(X1500m)),na.rm=T)) but it doesn't give me the mean.

I know that I can export the dataframe in a vector and after delete NA values, but I'm working with data frame with a lot of variables and It would be a little tired.

Was it helpful?

Solution 2

dput(timedf)
structure(list(X1500m = c("0:04:13", "0:04:06", "0:03:50", "0:03:42", 
NA, NA, NA, "0:03:59", NA, NA, NA, "0:03:50")), .Names = "X1500m", row.names = c(NA, 
-12L), class = "data.frame")

# testing my hunch expressed above that you needed to extract from the dataframe first:
times(mean(as.numeric(times(timedf$X1500m)),na.rm=T))

Warning in convert.times(times., fmt) : NAs introduced by coercion
Warning in convert.times(times., fmt) : NAs introduced by coercion
Warning in convert.times(times., fmt) : NAs introduced by coercion
Warning in convert.times(times., fmt) :
  time-of-day entries out of range in positions NA,NA,NA,NA,NA,NA set to NA
[1] 00:03:57

Boy, the times function really, really, wants you to see that you have NA's doesn't it. It does eventually get around to delivering a sensible mean.

OTHER TIPS

This should work for you -

timearray <- c(
  '0:04:13',
'0:04:06',
'0:03:50',
'0:03:42',
  NA
)

timearray <- strptime(timearray,'%H:%M:%S')
mean(timearray, na.rm = TRUE)

The result will include a date which you can remove, or retain, depending on your usage.

Using this chron library this can help

library(chron)
s = c("00:04:13", "00:04:06", "00:03:50", "00:03:42", NA, NA, NA, "00:03:59", NA, NA,NA, "0:03:50")
#format the time to a date format
strptime(s, format = '%H:%M:%S')
times <- chron(times = s)
mean(times,na.rm=TRUE)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top