# randomly generate either -1 or 1 [closed]

How do I generate values either -1 or 1 in R ?

sample(0:1,10,replace=T) produces random 10 samples of either 1 or 0.

If I modify this code to sample(-1:1,10,replace=T) I see three different values -1 or 0 or 1. I am just interested in -1 or 1.

Any advice or suggestions are much appreciated.

• I'm not saying that there's not a more direct or better way to do this. But note that if x is 0 or 1, then 2 * x - 1 maps 0 into -1 and 1 into 1. – Mark L. Stone Jun 9 '16 at 17:53
• @MarkL.Stone thanks Mark I can use various transformation. I am looking for a function that will avoid requiring extra lines of codes – bison2178 Jun 9 '16 at 17:57

• Exactly. -1:1 produces the sequence -1,0,1. Instead use sample(c(-1,1),10,replace=T) – Stephan Kolassa Jun 9 '16 at 17:53