[R] to modify a matrix : Summary
Mitsuo Igarashi
mitsu5 at ruby.famille.ne.jp
Sun Feb 9 09:08:02 CET 2003
I truly thank for evrybody to give me many very
good answers and suggestions.
I like to summarize the replies with their results
when excuted on R and with my comments.
My question is
> x <- matrix(1:10.,5)
> x
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
there is a matrix. On condition x[? ,1]=3, how to modify the
appropriate location to be x[? ,2] * 5.
SUMMARY
(1) x[,2] <- x[,2]*(1+4*(x[,1]==3))
good result, a little bit tricky.
(2) x[,2] <- ifelse(x[,1]==3, x[,2]*5, x[,2])
good result, easy to be understood.
(3) for(i in 1:5) {if (x[,1]==3) {x[,2] <- 5*x[,2]}}
unable to get any modification, theoretically easily undrstandable
from a programmer.
(4) rowstochange <- x[,1]==3
x[rowstochange,2] <- x[rowstochange,2]*5
good result, to give many suggetions.
When I excute "rowstochange <- x[,1]==3", I have
> rowstochange
[1] FALSE FALSE TRUE FALSE FALSE .
This is my first time to realize the meaning of the
expression of "x[,1]==3". This short sentence has inclusively
the way of "for", "repeat", and/or "if" clauses.
This is the wonderful part of R and the difficult part.
(5) x[x[,1]==3,2] <- x[x[,1]==3,2]*5
good result, simple, direct and straight.
My Best Gegards to everyone concerned.
-------========--------
mitsu5
mitsu5 at ruby.famille.ne.jp
More information about the R-help
mailing list