[R] replace() in matrix

Mark Myatt mark at myatt.demon.co.uk
Tue Jul 3 11:07:12 CEST 2001


Tord,

Writes:

>How do I replace values of a matrix, for exemple I want the matrix
>
>1      24      1       1       1
>24     1       1       1       1
>1      1       1       45      104
>1      1       45      1       92
>1      1       104     92      1
>
>to be replaced by 
>
>0      24      0       0       0
>24     0       0       0       0
>0      0       0       45      104
>0      0       45      0       92
>0      0       104     92      0
>
>Could someone please help me with that?

Use an index:

        your.mat.data <- c(1, 24, 1, 1, 1, 24, 1, 1, 1, 1, 1, 1, 1, 45,
                           104, 1, 1, 45, 1, 92, 1, 1, 104, 92, 1)

        your.mat <- matrix(data = your.mat.data, 
                           nrow = 5,
                           ncol = 5,
                           byrow = TRUE)

        your.mat

        your.mat[your.mat == 1] <- 0

        your.mat

The index is [your.mat == 1].

An alternative is to use the replace() function:

        your.mat.data <- c(1, 24, 1, 1, 1, 24, 1, 1, 1, 1, 1, 1, 1, 45,
                           104, 1, 1, 45, 1, 92, 1, 1, 104, 92, 1)

        your.mat <- matrix(data = your.mat.data, 
                           nrow = 5,
                           ncol = 5,
                           byrow = TRUE)

        your.mat

        your.mat <- replace(your.mat, your.mat == 1, 0)

Mark


--
Mark Myatt


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list