用NAs计算变量hh:mm:ss的平均值

时间:2013-12-10 18:01:17

标签: r dataframe statistics mean na

您好我想要计算具有NA值的变量hhmmss的平均值。

     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

如果我没有NA个值,我可以使用library(chron)和此命令times(mean(as.numeric(times(X1500m))))计算平均值。

我使用times(mean(as.numeric(times(X1500m)),na.rm=T))但它没有给我平均值。

我知道我可以在向量中导出数据帧并在删除NA值之后,但我正在使用包含大量变量的数据框,这会有点累。

3 个答案:

答案 0 :(得分:1)

这应该适合你 -

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)

结果将包括您可以删除或保留的日期,具体取决于您的使用情况。

答案 1 :(得分:0)

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

男孩,时代的功能真的,真的,希望你看到你有NA不是吗。它最终会提供一个合理的平均值。

答案 2 :(得分:0)

使用此chron库可以提供帮助

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)