Search code examples
rrandomadditionsubtraction

Function that do addition or subtraction randomly


I wonder if there is a function that can do addition or subtraction operator randomly:

x +- y

Solution

  • 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