[R] to modify a vector
Henrik Bengtsson
hb at maths.lth.se
Mon Feb 10 02:57:03 CET 2003
Hi, if I understand you correctly, you would like to change the value of
all elements with current value of 3 to 9. This is how you do it:
a1 <- c(1,2,3,4,3,5)
idx <- (a1 == 3)
a1[idx] <- 9
or in one line
a1[a1 == 3] <- 9
Look at 'idx' above. It is a logical vector of the same length as 'a1',
i.e.
idx: FALSE FALSE TRUE FALSE TRUE FALSE
When you then do 'a1[idx]' you select only those elements for which idx
is TRUE, here it is the third and the fifth. 'a1[idx] <- 9' selects
those elements and then assign the value 9 to them. Details: You could
also have done
idx <- which(a1 == 3)
where 'idx' then becomes equal to c(3,5), giving 'a1[c(3,5)] <- 9',
which gives identical results (of course).
Hope this helps
Henrik Bengtsson
> -----Original Message-----
> From: r-help-admin at stat.math.ethz.ch
> [mailto:r-help-admin at stat.math.ethz.ch] On Behalf Of Mitsuo Igarashi
> Sent: den 8 februari 2003 17:42
> To: r-help at stat.math.ethz.ch
> Subject: [R] to modify a vector
>
>
> Hi All.
>
> I am quite a newbie to R.
> This is a basic question.
>
> I like to modify elements of a vector.
> For Example:
> a1 <- c(1,2,3,4,3,5)
>
> TThe following program sentence does not work but the intention is;
>
> if (a1==3) a1*3 .
>
> 3 in the vector should be changed to 9, and
> the resulted vector is (1,2,9,4,9,5).
>
> How can I get the result?
>
> Thanks in advance for help.
> -------========--------
> mitsu5
> mitsu5 at ruby.famille.ne.jp
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/> r-help
>
>
More information about the R-help
mailing list