如何在r中创建索引矩阵?

时间:2018-05-07 16:04:46

标签: r

我需要绘制[-10,10] x [-10,10]的平方,这意味着我需要21 x 21 = 441点

具体来说,我需要一个矩阵:

X[1,] = x points = -10, -10, ..., -10, -9, -9, ..., -9, ..., 10
X[2, ] = y points = -10, -9, ...,  10, -10, -9, ..., 10, ..., 10
X[3, ] = all zeros

如何在不执行for循环的情况下生成此矩阵(请原谅pseduocode):

arr = c()
for(x1 in -10:10) {
    for(x2 in -10:10) {
       arr.append(x1)
       arr.append(x2)
       arr.append(0)
    }
}
M <- matrix(arr, nrow=3, ncol=441)

如果有人能帮助我,我将不胜感激!

1 个答案:

答案 0 :(得分:2)

我们可以使用expand.grid函数来完成大部分繁重工作:

t(cbind(expand.grid('x1' = -10:10, 'x2' = -10:10), 'zero' = 0))

以下是前五列:

     [,1] [,2] [,3] [,4] [,5]
x1    -10   -9   -8   -7   -6
x2    -10  -10  -10  -10  -10
zero    0    0    0    0    0

一个更简单的版本,正如@Frank所建议的那样:

t(expand.grid('x1' = -10:10, 'x2' = -10:10, 'zero' = 0))

如果您正在使用tidyverse

library(tidyr)
data.frame(x1 = -10:10, x2 = -10:10, zero = 0) %>%
    expand(x1, x2, zero) %>%
    t()