Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sapply 2 vectors

Tags:

r

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.

like image 629
Paolo Avatar asked May 13 '26 00:05

Paolo


2 Answers

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.

like image 181
Andrie Avatar answered May 14 '26 15:05

Andrie


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
like image 42
IRTFM Avatar answered May 14 '26 13:05

IRTFM



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!