Skip to content
Prev 306098 / 398506 Next

Confused by code?

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: