# [R] to modify a matrix

John Fox jfox at mcmaster.ca
Sat Feb 8 16:30:03 CET 2003

```Dear Mitsuo,

It isn't completely clear to me what the criterion is for selecting
elements, but if you want to change 8 to 40, but aren't sure where 8 is (or
8s are), then the following will work:

x[x==8] <- 40

The trick here is to index the matrix as a vector (since matrices in R are
vectors with a dim attribute).

More generally, there's a great deal of free information available about
manuals supplied with the R distribution and other material available from
the R web site.

John

At 12:04 AM 2/9/2003 +0900, 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?

-----------------------------------------------------
John Fox
Department of Sociology
McMaster University