conditionally multiply a vector by another r

2019-07-29 11:12发布

问题:

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

回答1:

One way is

unsplit(Map(`*`, split(trans, trans>=0), 
               list(negtrans, postrans)),trans>=0)
#[1]  -2  12  50 -10  -6 336   0


回答2:

Just multiply the corresponding entries with negtrans or postrans as required.

i <- which(trans < 0)
trans[i] <- trans[i] * negtrans
trans[-i] <- trans[-i] * postrans

However you will have a problem if the lengths of i and negtrans don't match.



回答3:

I like akrun's answer for form, but it turns out not so great.

EDIT: here's a pretty dumb solution which is essentially the same as konvas' :

trans[trans<0]<-trans[trans<0]*negtrans
trans[trans>0]<-trans[trans>0]*postrans

And here's how it worked out:

trans<-sample(-100:100,1e5,rep=TRUE)
negtrans<-1:1e3
postrans<-1e4:100e4

    Unit: microseconds
                              expr     min      lq  median      uq
   carl(trans, negtrans, postrans)   6.415   7.697   8.126  11.546
  akrun(trans, negtrans, postrans) 204.832 210.390 223.220 234.337
 konvas(trans, negtrans, postrans)   5.560   5.987   6.415  10.263
     max neval
  29.934     5
 376.308     5
  15.395     5