Paolo
Paolo

Reputation: 1637

sapply 2 vectors

Let's say I have 2 lists

divisor = c(0, 1, 1, 7, 7, 8, 8, 8, 9 )
remainder = c(99,  0,  1,  1, 99,  0,  1, 99,  0)

I want a divisor element to be element + 1 if its corresponding remainder is NOT 0. The final answer should look like:

updated.divisor = (1, 1, 2, 8, 8, 8, 9, 9, 9)

How would I do this using sapply?

So far I have

sapply(remainder, function(x) {
    if x != 0{
       #divisor = divisor + 1
    }
    else{
       #divisor = divisor + 0
    }
}

P.S. I could probably use a nested loop but I want to be able to do this using sapply.

Upvotes: 2

Views: 381

Answers (2)

IRTFM
IRTFM

Reputation: 263342

To your comment: If you wanted an apply type solution you would use mapply because it allows you to process two arguments "alongside each other":

mapply( function(x,y) {x + !(y==0)}, x=divisor, y=remainder)
#[1] 1 1 2 8 8 8 9 9 9

An ifelse solution would make sense, too:

 ifelse(remainder !=0, divisor+1, divisor)
#[1] 1 1 2 8 8 8 9 9 9

Upvotes: 5

Andrie
Andrie

Reputation: 179428

You don't need a loop:

divisor + (remainder!=0)
[1] 1 1 2 8 8 8 9 9 9

This is one of the most fundamental principles of R: all basic operations (and many functions) accept vectors as input and perform the operation on all elements of that vector at the same time.

Upvotes: 11

Related Questions