[R] to modify a matrix
Jonathan Baron
baron at cattell.psych.upenn.edu
Sat Feb 8 16:21:02 CET 2003
On 02/09/03 00:04, Mitsuo Igarashi wrote:
>Hi All.
>
>I am quite a newbie to R.
>This is a next basic question.
>
>I have a matrix;
>> x <- matrix(1:10.,5)
>> x
> [,1] [,2]
>[1,] 1 6
>[2,] 2 7
>[3,] 3 8
>[4,] 4 9
>[5,] 5 10
>
>I like to get a modified matrix as follows;
> [,1] [,2]
>[1,] 1 6
>[2,] 2 7
>[3,] 3 8 * 5 -> 40
>[4,] 4 9
>[5,] 5 10
>
>The following expression does not work.
> if (x[x[,1]==3]) x[x[,1]==3],2]*5
>
>How can I obtain a right expresion to get a modified matrix?
This will do it:
x[,2] <- x[,2]*(1+4*(x[,1]==3))
But probably you want to do it with something like "if". So:
x[,2] <- ifelse(x[,1]==3, x[,2]*5, x[,2])
Or a loop:
for(i in 1:5) {if (x[,1]==3) {x[,2] <- 5*x[,2]}}
--
Jonathan Baron, Professor of Psychology, University of Pennsylvania
R page: http://finzi.psych.upenn.edu/
More information about the R-help
mailing list