说我有一个矩阵m
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 1 3 5 9 11 15 17 21 27
[2,] 0 0 2 4 8 10 14 16 20 26
[3,] 0 0 0 2 6 8 12 14 18 24
[4,] 0 0 0 0 4 6 10 12 16 22
[5,] 0 0 0 0 0 2 6 8 12 18
[6,] 0 0 0 0 0 0 4 6 10 16
[7,] 0 0 0 0 0 0 0 2 6 12
[8,] 0 0 0 0 0 0 0 0 4 10
[9,] 0 0 0 0 0 0 0 0 0 6
[10,] 0 0 0 0 0 0 0 0 0 0
dput是:
structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 5, 4, 2, 0, 0, 0, 0, 0,
0, 0, 9, 8, 6, 4, 0, 0, 0, 0, 0, 0, 11, 10, 8, 6, 2, 0, 0, 0,
0, 0, 15, 14, 12, 10, 6, 4, 0, 0, 0, 0, 17, 16, 14, 12, 8, 6,
2, 0, 0, 0, 21, 20, 18, 16, 12, 10, 6, 4, 0, 0, 27, 26, 24, 22,
18, 16, 12, 10, 6, 0), .Dim = c(10L, 10L))
说我有矢量p
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
dput是:
c(2L, 3L, 5L, 7L, 11L, 13L, 17L, 19L, 23L, 29L)
我想将矩阵中不是p的所有值设置为零
我如何优雅地做到这一点?
答案 0 :(得分:1)
尝试
m1[!m1 %in% p] <- 0
或者与上一个问题一样,我们可以将逻辑索引与&#39; m1&#39;相乘。所以&#39; TRUE / FALSE gets coerced to binary (
1 / 0`)并乘以&#39; 0 / FALSE&#39;具有&#39; m1&#39;的相应元素的值给出了&#39; 0&#39; 0作为结果。
m1 <- (m1 %in% p)*m1
m1 <- structure(c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 3L, 2L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 5L, 4L, 2L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 9L, 8L, 6L, 4L, 0L,
0L, 0L, 0L, 0L, 0L, 11L, 10L, 8L, 6L, 2L, 0L, 0L, 0L, 0L, 0L,
15L, 14L, 12L, 10L, 6L, 4L, 0L, 0L, 0L, 0L, 17L, 16L, 14L, 12L,
8L, 6L, 2L, 0L, 0L, 0L, 21L, 20L, 18L, 16L, 12L, 10L, 6L, 4L,
0L, 0L, 27L, 26L, 24L, 22L, 18L, 16L, 12L, 10L, 6L, 0L), .Dim = c(10L,
10L))
p <- c(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71)