Re: [R] setting elements of matrix

From: Sundar Dorai-Raj <sundar.dorai-raj_at_pdf.com>
Date: Wed 25 May 2005 - 22:46:13 EST

Richard Valliant wrote:
> This is, no doubt, an easy problem, but I need help. I want to set
> values in a matrix based on entries in a vector. Here is an example:
>
> D is an r x m matrix initilized to all zeroes. r=6, m=5 in the
> example.
>
> Ro <- c(1, 3, 4, 4, 6)
> Co <- c(1, 2, 3, 4, 5)
>
> I want to set D[Ro[j], Co[j] ] to 1. So, D becomes
>
> 1 0 0 0 0
> 0 0 0 0 0
> 0 1 0 0 0
> 0 0 1 1 0
> 0 0 0 0 0
> 0 0 0 0 1
>
> A loop works but is slow, which matters since this is being done many
> times in a simulation.
>

How about:

D <- matrix(0, 6, 5)
D[cbind(Ro, Co)] <- 1

--sundar



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed May 25 22:52:47 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:05 EST