Jim Maas
Jim Maas

Reputation: 1729

replace a for loop, but with which apply statement?

I'm attempting to replace some very complex for loops with apply statements in old legacy code. This is a small example for loop as an example

old.array <- c(15:24)
new.array <- old.array

for (i in 4:length(old.array)) {
    new.array[i] <- old.array[i-2] + old.array[i-3]
}

Any suggestions on which way to go to replace this with an apply (or plyr) function would be most helpful. The problem for me arises from the placeholder such as [i -2] in the formula.

Upvotes: 2

Views: 110

Answers (2)

jlhoward
jlhoward

Reputation: 59345

No need to a for loop or any of the apply(...) functions.

len <- length(old.array)
new.array <- old.array
new.array[4:len] <- old.array[2:(len-2)] + old.array[1:(len-3)]

@SvenHohenStein's comment below is correct. In the revised code above the vectors are the same length (len-3).

Upvotes: 1

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

Here's a way to do it:

new.array <- c(old.array[1:3], 
               filter(head(old.array, -2), c(1, 1), sides = 1)[-1])
# [1] 15 16 17 31 33 35 37 39 41 43

Upvotes: 1

Related Questions