[R] Re-assigning vector elements based on their initial values.

John Fox jfox at mcmaster.ca
Sat Feb 1 13:21:03 CET 2003


Dear Rex,

You can use if.else, which is vectorized:

         > v.new <- ifelse(v < 0, -v/2, v)
         > v.new
         [1]  5.0  5.0  1.5  1.5  7.0  8.0 10.0

(By the way, the solution that you suggested using a loop works, but for 
some reason the sign is wrong in the result that you printed; notice that 
your "else" clause does nothing -- you probably meant to assign to v.new 
not v -- and is unnecessary in any event.)

I hope that this helps,
  John



At 07:38 PM 1/31/2003 -0700, Rex_Bryan at urscorp.com wrote:
>Is there an eloquent solution to re-assign vector element values?
>I have a vector which contains chemical data, some of them are "flagged" as
>non-detected values by their negative values.
>I can find the statistics on the positive values in vector "v"  simply by
>typing:
> >v<- c(5,5,-3,-3,7,8,10)
>
> > v[(v>0)]
>[1] 5  5  7  8  10
>
>I can also convert to positive values by
> >asb(v)
>[1]  5  5  3  3  7  9  10
>
>I then can do mean() and var() etc.
>
>But when I want to come up with a way to change a negative value to a
>postive 1/2 value I couldn't come up with a
>nice way using "vectoral syntax" to do it.  In the method I came up with , I
>discovered that I have to pre-define a new vector "v.new" or I get an error.
>
> >v.new <-v
>
>then I have to loop through all of the elements!
>
> >for(i in 1:length(v)){ if (v[i] < 0) v.new[i] <-  -1*v[i]/2 else v[i] <-
>v[i]}
> > v.new
>[1]  5.0  5.0  -1.5  -1.5  7.0  9.0  10.0
>
>This works but seems labored given the previous crisp vector operations.

-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------




More information about the R-help mailing list