0

I want to calculate the mean of the 1st value to the 10th, then calculate the mean for the 11th value to the 15th and then calculate the mean for the 16th value to the 18th and so. So basically I want to calculate the mean for the Xth values where X are different values given in a vector. For example:

y=c(1,1,2,3,2,1,4,5,3,6,7,5,6,7,8,4,2,4)
x=c(10,5,3)

Then, the first, second and third means would be:

sum(1+1+2+3+2+1+4+5+3+6)/10
sum(7+5+6+7+8)/5
sum(4+2+4)/3

Can you help me please? Thanks!

2 Answers2

3

You can borrow the splitAt function from this answer:

splitAt <- function(x, pos) {
  unname(split(x, cumsum(seq_along(x) %in% pos)))
}

To split y you need to start at 1 and add 1 to the cumulative sum of the values in x:

splitAt(y, c(1, cumsum(x)+1))

[[1]]
 [1] 1 1 2 3 2 1 4 5 3 6

[[2]]
[1] 7 5 6 7 8

[[3]]
[1] 4 2 4

Now you have a list, so you can lapply or sapply:

sapply(splitAt(y, c(1, cumsum(x)+1)), mean)

[1] 2.800000 6.600000 3.333333
neilfws
  • 32,751
  • 5
  • 50
  • 63
1
x <- cumsum(x)
x <- c(1,x)
for(i in 1:(length(x)+1)){
    print(mean(y[x[i-]:x[i+1]]))
neilfws
  • 32,751
  • 5
  • 50
  • 63
Tomo
  • 580
  • 6
  • 5