Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally multiply a vector by another r

I have the following vector

trans<- c(-2,3,10,-5,-2,56,0)

and I want to multiply each element by a choice of two vectors depending on whether the initial number is positive or negative

negtrans<-c(1,2,3)
postrans<-c(4,5,6,7)

the result should look like this -2 12 50 -10 -6 336 0

the key here is to keep the order intact

like image 355
ulrich Avatar asked Mar 29 '26 21:03

ulrich


1 Answers

One way is

unsplit(Map(`*`, split(trans, trans>=0), 
               list(negtrans, postrans)),trans>=0)
#[1]  -2  12  50 -10  -6 336   0
like image 58
akrun Avatar answered Apr 01 '26 07:04

akrun



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!