I wonder if there is a function that can do addition or subtraction operator randomly:
x +- y
The question boils down to getting -1
or 1
in random fashion. You can get it using sample
:
x + sample(c(-1,1),size=1)*y
or runif
:
x + sign(runif(n=1,min=-1,max=1))*y
If x
and y
are vectors, you can generate sequence of numbers -1
and 1
of the same length as the length of x
, as @BondedDust suggested:
x + sample(c(-1,1),size=length(x),replace=T)*y
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With