Reputation: 1354
So I want to extract both the location and the value of a vector. Here is the example code:
x <- matrix(1:96, nrow = 8)
x
y <- c(0,8,0,0,0,7,0,0,0)
y
which(y > 0)
This gives and output of
[1] 2 6
I want to then find the values of x[2,8]
and x[6,7]
. I have tried to do:
test <- ifelse(y > 0, x[which(y > 0 ),y], 0)
But that only produces
[1] 0 62 0 0 0 62 0 0 0
Which is actually x[6,8]
. There is probably a relatively easy way to do this in R and I am missing something fairly simple.
Upvotes: 2
Views: 79
Reputation: 886938
We create a row/column numeric index based on which(y>0)
and y[y>0]
, cbind
it and use that to extract the values in 'x'
x1 <- x[cbind(which(y>0), y[y>0])]
x1
#[1] 58 54
If we want to replace the non-zero elements in 'y', use the condition y>0
and replace those 'y' values with 'x1'.
y[y>0] <- x1
y
#[1] 0 58 0 0 0 54 0 0 0
Or if we don't need to change the initial 'y' vector
y1 <- replace(y, which(y > 0), x1)
y1
#[1] 0 58 0 0 0 54 0 0 0
Upvotes: 2