Ben
Ben

Reputation: 21625

How to get the mean of the last 1, 2, 3, ... elements in a vector

I have a vector like

vec<-c(1,5,3,6,10)

How do I quickly get the median of the last 1, 2, 3,... elements in the list? In other words, I want to return the median for each of the following subvectors

c(10)
c(6,10)
c(3,6,10) ...

So my final result should be a vector equivalent to c(10,8,6,4.5,3). I know I can use median(tail(vec,n)) to get the median of the last n elements, but how do I apply this for n over the set 1:length(vec) without using a slow for loop?

Upvotes: 0

Views: 135

Answers (1)

agstudy
agstudy

Reputation: 121578

For example using tail , you can loop over your vector and extract the nth last elements:

sapply(seq_along(vec),
       function(x)median(tail(vec,x)))
[1] 10.0  8.0  6.0  5.5  5.0

Upvotes: 2

Related Questions