Reputation:
Suppose that I have lower triangular matrix i.e.,
w1 <- c(0,0.6,0.3,0.6,0.7,
0,0,0.6,0.6,0.7,
0,0,0,0.6,0.6,
0,0,0,0,0.7,
0,0,0,0,0)
w1 <- matrix(w1,5,5)
Then, I would like the second matrix to be a lower triangular matrix, say w2
where each non-zero values of w2
are 1-the corresponding values of w1
.
Like this:
w2 <- c(0,0.4,0.7,0.4,0.3,
0,0,0.4,0.4,0.3,
0,0,0,0.4,0.4,
0,0,0,0,0.3,
0,0,0,0,0)
w2 <- matrix(w2,5,5)
w <- list(w1, w2)
How can I get w2
automatically?
Upvotes: 0
Views: 65
Reputation: 12559
You can use the indexing of lower.tri()
also on the left side:
w2new <- matrix(0, dim(w1)[1], dim(w1)[2])
w2new[lower.tri(w2new)] <- 1 - w1[lower.tri(w1)]
Upvotes: 1
Reputation: 3038
Since most operations in R are vectorised, you can simply use ifelse
to either subtract 1 - w1
, or if w1
is zero, retain zero.
ifelse(w1 == 0, 0, 1 - w1)
Upvotes: 1