[R] setting elements of matrix
Sundar Dorai-Raj
sundar.dorai-raj at pdf.com
Wed May 25 14:46:13 CEST 2005
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
More information about the R-help
mailing list