[R] Confused by code?

Rui Barradas ruipbarradas at sapo.pt
Mon Sep 24 02:29:34 CEST 2012


Hello,

It is pretty basic, and it is deceptively simple. The worst of all :)
When you index a matrix 'x' by another matrix 'z' the index can be a 
logical matrix of the same dimensions or recyclable to the dims of 'x', 
it can be a matrix with only two columns, a row numbers column and a 
column numbers one, or your case.

In your case, 'z' is coerced to vector, and the values in 'z' are taken 
to be indexes to 'x'. But since you only have two distinct values and 
one of them is zero, it will only return x[1] three times (there are 
three 1s in 'z'). The same goes for 'y'.

Correct:

# Create an index matrix
z.inx <- which(z == 1, arr.ind = TRUE)
z.inx

# Test
x1 <- x2 <- x3 <- x # Use copies to test
x1[z == 1] <- y[z == 1]
x2[z.inx] <- y[z.inx]
# 1 and 0 to T/F
x3[as.logical(z)] <- y[as.logical(z)]

x1
identical(x1, x2)
identical(x1, x3)


Hope this helps,

Rui Barradas

Em 23-09-2012 21:52, Bazman76 escreveu:
> x<-matrix(c(1,0,0,0,1,0,0,0,1),nrow=3)
>> y<-matrix(c(0,0,0,1,0,0,1,1,0),nrow=3)
>> z<-matrix(c(0,1,0,0,1,0,1,0,0),nrow=3)
>> x[z]<-y[z]
> The resultant matrix x is all zeros except for the last two diagonal cells
> which are 1's.
> While y is lower triangualr 0's with the remaining cells all ones.
>
> I really don't understand how this deceptively simple looking piece of code
> is giving that result can someone explain please.
> I'm obviously missing something pretty basic so please keep your answer
> suitably basic.
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Confused-by-code-tp4643946.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list