Hi All,
I have one difficulty in using the conditional if statement
Assume ,
x <- -1:4
x
[1] -1 0 1 2 3 4
if x is lees than want I want to add 1 and I used the following command
if(x<0) {x=x+1}
Warning message:
In if (x < 0) { :
the condition has length > 1 and only the first element will be
used> x
[1] 0 1 2 3 4 5
That command added 1 to each element.
But I want like this 0 0 1 2 3 4
Can anybody help me?
Thanks
Val
[[alternative HTML version deleted]]
You need ifelse() instead of if(). On Wed, Mar 7, 2012 at 2:12 PM, Val <valkremk at gmail.com> wrote:> Hi All, > > I have one difficulty in using the conditional if statement > > Assume , > > x <- -1:4 > ?x > [1] -1 ?0 ?1 ?2 ?3 ?4 > > if x is lees than want I want to add 1 and I used the following command > ?if(x<0) {x=x+1} > > Warning message: > In if (x < 0) { : > ?the condition has length > 1 and only the first element will be used >> x > [1] 0 1 2 3 4 5 > ?That command added 1 to each element. > > But I want like this ?0 0 1 2 3 4 > > Can anybody help me? > > Thanks > Val-- Sarah Goslee http://www.functionaldiversity.org
Try> ifelse( x < 0, x + 1, x)[1] 0 0 1 2 3 4 See also ?ifelse. HTH, Jorge.- On Wed, Mar 7, 2012 at 2:12 PM, Val <> wrote:> Hi All, > > I have one difficulty in using the conditional if statement > > Assume , > > x <- -1:4 > x > [1] -1 0 1 2 3 4 > > if x is lees than want I want to add 1 and I used the following command > if(x<0) {x=x+1} > > Warning message: > In if (x < 0) { : > the condition has length > 1 and only the first element will be used > > x > [1] 0 1 2 3 4 5 > That command added 1 to each element. > > But I want like this 0 0 1 2 3 4 > > Can anybody help me? > > Thanks > Val > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >[[alternative HTML version deleted]]