在R

时间:2017-10-21 17:42:00

标签: r matrix vector random

如何将矢量a<-c(1,2,3,4,5,6)置于矩阵m<-matrix(0, nrow = 10, ncol = 10)中的ramdom位置?

载体必须在一起:

       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    0    0    0    0    0    0    0    0     0
 [2,]    1    0    0    0    0    0    0    0    0     0
 [3,]    2    0    0    0    0    0    0    0    0     0
 [4,]    3    0    0    0    0    0    0    0    0     0
 [5,]    4    0    0    0    0    0    0    0    0     0
 [6,]    5    0    0    0    0    0    0    0    0     0
 [7,]    6    0    0    0    0    0    0    0    0     0
 [8,]    0    0    0    0    0    0    0    0    0     0
 [9,]    0    0    0    0    0    0    0    0    0     0
[10,]    0    0    0    0    0    0    0    0    0     0

它必须是水平,垂直或对角线 我试过了:

start = sample.int(length(m), 1)
m[start:(start+length(a)-1)] = a

但不能发生以下情况:

       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    0    0    0    0    0    5    0    0     0
 [2,]    0    0    0    0    0    0    6    0    0     0
 [3,]    0    0    0    0    0    0    0    0    0     0
 [4,]    0    0    0    0    0    0    0    0    0     0
 [5,]    0    0    0    0    0    0    0    0    0     0
 [6,]    0    0    0    0    0    0    0    0    0     0
 [7,]    0    0    0    0    0    1    0    0    0     0
 [8,]    0    0    0    0    0    2    0    0    0     0
 [9,]    0    0    0    0    0    3    0    0    0     0
[10,]    0    0    0    0    0    4    0    0    0     0

由于

1 个答案:

答案 0 :(得分:1)

采样与a大小相同的1d索引,然后在这些索引处将矢量分配给m

m[sample.int(length(m), length(a))] <- a
m
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    0    6    0    0    0    0    0    0    0     0
# [2,]    0    0    0    0    0    4    0    0    0     0
# [3,]    0    3    0    1    0    0    0    0    5     0
# [4,]    0    0    0    0    0    0    0    0    0     0
# [5,]    0    0    0    0    0    0    0    0    0     0
# [6,]    0    0    0    0    0    0    0    0    0     0
# [7,]    0    0    0    0    0    0    0    0    0     0
# [8,]    0    0    0    0    0    0    0    0    2     0
# [9,]    0    0    0    0    0    0    0    0    0     0
#[10,]    0    0    0    0    0    0    0    0    0     0

如果向量需要是连续的,您可以对起始索引进行采样,然后使用范围索引进行分配:

start = sample.int(length(m), 1)
m[start:(start+length(a)-1)] = a

m
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    0    0    0    0    0    0    0    0    0     0
# [2,]    0    0    0    0    0    0    0    0    0     0
# [3,]    0    0    0    0    0    0    0    0    0     0
# [4,]    0    0    0    0    0    0    0    0    0     0
# [5,]    1    0    0    0    0    0    0    0    0     0
# [6,]    2    0    0    0    0    0    0    0    0     0
# [7,]    3    0    0    0    0    0    0    0    0     0
# [8,]    4    0    0    0    0    0    0    0    0     0
# [9,]    5    0    0    0    0    0    0    0    0     0
#[10,]    6    0    0    0    0    0    0    0    0     0