How can I randomly change the sign of numbers in a vector?

Viewed 137

I have a long vector of numbers that vary in the their sign (e.g.):

data <- c(1,-23,67,-21,10,32,64,-34,-6,10)

Working in R, how do I create a new vector that contains the same list of numbers, but give them a random sign (either positive or negative)? For each number, the probability of it being negative should be 0.5.

1 Answers

There are a bunch of options but

sample(c(-1,1), size=length(data), replace=TRUE) * abs(data)

should work. You could also multiply by sign(runif(length(data))-0.5) or sign(runif(length(data),-1,1)) [either of which should be a little more efficient than sample(), although in this case it hardly matters].

Related