-3
$\begingroup$

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.

$\endgroup$
  • 3
    $\begingroup$ 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. $\endgroup$ – Mark L. Stone Jun 9 '16 at 17:53
  • $\begingroup$ @MarkL.Stone thanks Mark I can use various transformation. I am looking for a function that will avoid requiring extra lines of codes $\endgroup$ – bison2178 Jun 9 '16 at 17:57
6
$\begingroup$

Instead of sampling from the range -1:1, sample from the list -1, 1.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.