[R] Extracting/setting elements from/in a matrix/array

Martin Maechler maechler at stat.math.ethz.ch
Mon Dec 31 14:48:51 CET 2001

>>>>> "Laurent" == Laurent Gautier <laurent at genome.cbs.dtu.dk> writes:

    Laurent> Dear all,

    Laurent> I had to extracts/set elements from/in a
    Laurent> matrix. Let say I have two vectors dim1 and dim2 of
    Laurent> indices in the respective two dimensions of a
    Laurent> matrix: I want to extract all the corresponding
    Laurent> elements. I the case of a nxn matrix, dim1 <- 1:n
    Laurent> and dim2 <- 1:n would extract the diagonal.

The solution to your problem has been part of the   S language
for ever :

    mat[ cbind(dim1, dim2) ]

Note that this is mentioned in help("[") and MASS and ...

    Laurent> I know one way would be to use the functions 'row'
    Laurent> and 'col', but the matrixes I have are can be
    Laurent> rather large. This is probably a detail but I was
    Laurent> looking for something that would avoid be bit more
    Laurent> memory friendly... I have made functions for that
    Laurent> purpose but I suspect somebody already did
    Laurent> something (which would be in R, but I could not
    Laurent> find it...).  For the sake of avoiding duplication
    Laurent> of similar things (hence making code more
    Laurent> readable), I would be happy to replace it in my
    Laurent> code.

    Laurent> Does anybody knows if such things already exists ?

    Laurent> Laurent Gautier CBS, Building 208, DTU PhD. Student
    Laurent> D-2800 Lyngby,Denmark tel: +45 45 25 24 85
    Laurent> http://www.cbs.dtu.dk/laurent
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