Mattia Mattia - 1 year ago 80
R Question

Extracting elements from a vector iteratively for further operations

Imagine we have the following vector:

x <- c(2, 13, 9, 12, 10, 19, 15, 17, 14, 3, 8, 20, 16, 4, 18, 6, 5, 1, 7, 11)


As is noticeable, the vector, lets call it X, has 20 observations.

Now, imagine the following:

k = 3


And that we want to extract (i+k-1)/2 elements from X, to get a new vector, call it "little X".

This implies that for the first element, i = 1, I would extract the following element:

for i = 1, extract (1+3-1)/2 = 3/2 = 1.5


In other words, the 1.5th element, which when rounded up becomes 2, so that the element I am extracting is in fact i = 2, and in this case 13.

How can I loop over the vector and apply the same procedure iteratively to end up with a new vector "little X" containing every (i+k-1)/2 elements?

Thanks.

Small edit

It is required that "little X" has length 18.
The reason why is as follows:

I have a vector containing the residuals observed at (i+k-1)/2 from rolling linear model. This vector has length 18 and is called "detrends".

I am trying to subtract "detrends" from the (i+k-1)/2 elements of X to get a fourth vector Y with length 18, called "Y".

Hence, "detrends" and the vector "little X" should be of equal length.

My results for Y should be:

{8., 11.3333, 10.3333, 13.6667, 14.6667, 17., 15.3333, 11.3333, 8.33333,
10.3333, 14.6667, 13.3333, 12.6667, 9.33333, 9.66667, 4., 4.33333, 6.33333}


Given that the detrends are:

{5.0000000 -2.3333333 1.6666667 -3.6666667 4.3333333 -2.0000000 1.6666667
2.6666667 -5.3333333 -2.3333333 5.3333333 2.6666667 -8.6666667 8.6666667
-3.6666667 1.0000000 -3.3333333 0.6666667}


Given some of the comments below, I have found that some of the elements are replicated too often. While I get some of the correct numbers, they are not in right oder.

Could someone clarify how I can get the desired output for Y, namely:

{8., 11.3333, 10.3333, 13.6667, 14.6667, 17., 15.3333, 11.3333, 8.33333,
10.3333, 14.6667, 13.3333, 12.6667, 9.33333, 9.66667, 4., 4.33333, 6.33333}


Where:

Y = "little X" - "detrends"


Thanks.

Answer Source
x[sapply(1:(length(x) - 2), function(i) { round(((i + k - 1)/2)) } )]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download