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

Rex_Bryan@urscorp.com RexBryan1 at attbi.com
Sat Feb 1 03:35:03 CET 2003


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.


REX




More information about the R-help mailing list