如何计算列中前4个观测值的平均值?

TWe*_*est 1 r max mean

如何计算列中前4个观测值的平均值?

c(12, 13, 15, 1, 5, 9, 34, 50, 60, 50, 60, 4, 6, 8, 12)
Run Code Online (Sandbox Code Playgroud)

例如,在上面我会有(50 + 60 + 50 + 60)/ 4 = 55.我只知道如何使用分位数,但它不适用于此.

有任何想法吗?

Aru*_*run 6

由于您只对前4项感兴趣,因此您可以使用partial sort而不是完全排序.如果你的矢量太大,你可能会节省很多时间:

x <- c(12, 13, 15, 1, 5, 9, 34, 50, 60, 50, 60, 4, 6, 8, 12)
idx <- seq(length(x)-3, length(x))
mean(sort(x, partial=idx)[idx])
# [1] 55
Run Code Online (Sandbox Code Playgroud)