Utkarsh Naiknaware
Utkarsh Naiknaware

Reputation: 126

Looping through selected values in R

I want to iterate a loop only for some values so I am using this:

present <- c(3,5,7,8)
for(i in present)
{
   print(i)
}

which gives me

[1] 3
[1] 5
[1] 7
[1] 8

however I need to jump to the next value within the loop, say I dont want 5 to be printed in above example.

I cannot use next since I want it in nested for like this

present <- c(3,5,7,8)
for(i in present)
{
    k <- i
    "Jump to next value of present"
    while(k < "The next value for i should come here")
    {
        k <- k + 1
        print(k)
    }
}

The output would be 3 4 5 6 7 8 but the condition must check value of k if it exceeds next value of i.

Is there anyway to accomplish this?

I'll take help of C to explain further,

for(i=0; i < 10; i++)
{
   for(k=i;k <= i+1;k++)
   {
       printf("%d", k);
   }
}

The link contains output of above code http://codepad.org/relkenY3

It is easy in C since next value is in sequence, but here next value is not known, hence the problem.

Upvotes: 0

Views: 1200

Answers (2)

IRTFM
IRTFM

Reputation: 263342

I suspect the answer is to use seq_along and use it as an index into "present", but as others have pointed out your code does not promise to deliver what you expect, even with that simple modification. The K <- K=1 assignment jumps ahead too far to deliver a value of 3 at any point and the termination condition is likewise not clear. It turns into an infinite loop in the form you construct. Work with this;

present <- c(3,5,7,8)
    for(i in seq_along(present))
    {
        k <- i
        while(k < length(present) )
        {
            k <- k + 1
            print(present[k])
        }
    }

Upvotes: 0

flodel
flodel

Reputation: 89057

What you should do is loop through two vectors:

x <- head(present, -1)
# [1] 3 5 7
y <- tail(present, -1)
# [1] 5 7 8

and the function to do that is mapply (have a look at ?mapply). A close translation of your pseudo-code would be:

invisible(mapply(function(x, y) while(x < y) {x <- x + 1; print(x)}, x, y))

but maybe you'll find this more interesting:

mapply(seq, x + 1, y)

Upvotes: 2

Related Questions