理解括号并乘以R中的标量矩阵

时间:2015-06-15 17:20:58

标签: r

假设我有矩阵(下面的输入):

> m
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0   -1   -3   -5   -9  -11  -15  -17  -21   -27
 [2,]    1    0   -2   -4   -8  -10  -14  -16  -20   -26
 [3,]    3    2    0   -2   -6   -8  -12  -14  -18   -24
 [4,]    5    4    2    0   -4   -6  -10  -12  -16   -22
 [5,]    9    8    6    4    0   -2   -6   -8  -12   -18
 [6,]   11   10    8    6    2    0   -4   -6  -10   -16
 [7,]   15   14   12   10    6    4    0   -2   -6   -12
 [8,]   17   16   14   12    8    6    2    0   -4   -10
 [9,]   21   20   18   16   12   10    6    4    0    -6
[10,]   27   26   24   22   18   16   12   10    6     0

我试图理解(我想要的结果)之间的区别:

> (m < 0) * 1
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    1    1    1    1    1    1    1    1     1
 [2,]    0    0    1    1    1    1    1    1    1     1
 [3,]    0    0    0    1    1    1    1    1    1     1
 [4,]    0    0    0    0    1    1    1    1    1     1
 [5,]    0    0    0    0    0    1    1    1    1     1
 [6,]    0    0    0    0    0    0    1    1    1     1
 [7,]    0    0    0    0    0    0    0    1    1     1
 [8,]    0    0    0    0    0    0    0    0    1     1
 [9,]    0    0    0    0    0    0    0    0    0     1
[10,]    0    0    0    0    0    0    0    0    0     0

并且,以下哪个不是我想要做的:

> m < 0 * (1)
       [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10]
 [1,] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
 [2,] FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
 [3,] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
 [4,] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
 [5,] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
 [6,] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE
 [7,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE
 [8,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE
 [9,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
[10,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

dbput

> dput(m)
structure(c(0L, 1L, 3L, 5L, 9L, 11L, 15L, 17L, 21L, 27L, -1L, 
0L, 2L, 4L, 8L, 10L, 14L, 16L, 20L, 26L, -3L, -2L, 0L, 2L, 6L, 
8L, 12L, 14L, 18L, 24L, -5L, -4L, -2L, 0L, 4L, 6L, 10L, 12L, 
16L, 22L, -9L, -8L, -6L, -4L, 0L, 2L, 6L, 8L, 12L, 18L, -11L, 
-10L, -8L, -6L, -2L, 0L, 4L, 6L, 10L, 16L, -15L, -14L, -12L, 
-10L, -6L, -4L, 0L, 2L, 6L, 12L, -17L, -16L, -14L, -12L, -8L, 
-6L, -2L, 0L, 4L, 10L, -21L, -20L, -18L, -16L, -12L, -10L, -6L, 
-4L, 0L, 6L, -27L, -26L, -24L, -22L, -18L, -16L, -12L, -10L, 
-6L, 0L), .Dim = c(10L, 10L))

1 个答案:

答案 0 :(得分:4)

*的优先级高于<

> 2 < 1 * 3
[1] TRUE
> (2 < 1) * 3
[1] 0
> 2 < (1 * 3)
[1] TRUE

在进行比较之前进行乘法运算。