【问题标题】:Calculate the mean of a variable hh:mm:ss with NAs使用 NA 计算变量 hh:mm:ss 的平均值
【发布时间】:2013-12-28 09:50:00
【问题描述】:

您好,我想计算具有 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 值之后,但我正在使用包含很多变量的数据框,这会有点累。

【问题讨论】:

  • 我认为问题可能在更高级别。看起来打印输出就像您从数据帧中所说的那样,您需要从数据帧的名称中提取“X1500m”列的值。

标签: r dataframe statistics mean na


【解决方案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)

结果将包含一个日期,您可以根据使用情况删除或保留该日期。

【讨论】:

  • @ChinmayPatil - ?strftime - %H Hours as decimal number (00–23). As a special exception times such as 24:00:00 are accepted for input, since ISO 8601 allows these. 为什么你说它不起作用?
【解决方案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

男孩,时代功能真的,真的,希望你看到你有 NA,不是吗。它最终确实可以提供一个合理的方法。

【讨论】:

    【解决方案3】:

    使用这个 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 2013-12-29
      • 2023-04-04
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多