Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an apply function on multiple subsets of a vector

I've been scrounging around for a solution for this for a while, but there doesn't seem to be anything that can solve this seemingly simple problem I'm having.

Long story short, I'm looking to run a function on multiple subsets of a vector, but I am trying to avoid a for loop.

As a simple example

x <- runif(20)

index <- round(runif(10,1,10))
[1] 7 8 4 6 9 3 1 2 8 7

Now what I'm trying to do is run an apply function that would find the (let's say) mean of the last 7 entries of x, then the last 8 entries of x, then the last 4 entries of x, etc, etc.

This would be using the tail(x, n) function in some way, but I've been getting erroneous results because the apply family of functions will either return one result for each element in its passed arguments (like in mapply) which won't work because length(x) != length(index), or one result for each element in the passed object (in this case, the 20 elements of x). I'm looking to get 10 means as the output.

Thoughts? Let me know if I can clear up the example somewhat.

like image 488
user3780892 Avatar asked Jan 31 '26 17:01

user3780892


1 Answers

You can still use xapply functions. You can try something like:

set.seed(1)
x <- runif(20)
index <- round(runif(10,1,10))
## [1] 5 5 9 8 4 1 4 6 3 9
sapply(index, function(n) mean(tail(x, n)))
## [1] 0.4622008 0.4622008 0.5185548 0.5222463 0.4519646 0.2787476 0.4519646
## [8] 0.4939800 0.2748015 0.5185548

Just to check:

mean(tail(x, 5))
## [1] 0.4622008
mean(tail(x, 9))
## [1] 0.5185548

Hope it helps,

alex

like image 137
alko989 Avatar answered Feb 03 '26 08:02

alko989



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!