我有一个转换为矩阵的图表。
g = sample_k_regular(10,3)
m =get.adjacency(g)
我想随机选择一些元素并转换为0 | 1.(如果为0则变为1,如果为1则变为0)。
如何做这项工作?
答案 0 :(得分:1)
您可以制作sample
个n
元素(示例中为10个)并进行更改
m1=as.matrix(m)
m1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 1 1 0 0 0 0 1 0
[2,] 0 0 0 0 1 0 0 0 1 1
[3,] 1 0 0 0 0 0 0 1 0 1
[4,] 1 0 0 0 1 0 1 0 0 0
[5,] 0 1 0 1 0 1 0 0 0 0
[6,] 0 0 0 0 1 0 1 0 0 1
[7,] 0 0 0 1 0 1 0 1 0 0
[8,] 0 0 1 0 0 0 1 0 1 0
[9,] 1 1 0 0 0 0 0 1 0 0
[10,] 0 1 1 0 0 1 0 0 0 0
set.seed(1)
ss=sample(length(m1),size = 10)
m1[ss]=1-m1[ss]
m1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 1 1 0 0 0 0 1 0
[2,] 0 0 0 0 1 0 1 0 1 1
[3,] 1 0 0 0 0 0 0 1 0 1
[4,] 1 0 0 0 1 0 1 0 0 0
[5,] 0 1 0 1 0 1 0 0 0 0
[6,] 1 0 0 0 1 0 1 0 1 1
[7,] 0 0 1 0 0 0 0 1 0 1
[8,] 0 0 1 0 0 1 1 0 1 0
[9,] 1 1 0 0 0 0 0 1 1 0
[10,] 0 0 1 0 0 1 0 0 0 0
排除对角线@ZheyuanLi告诉
您可以计算diad位置并从样本数据中排除:
m1=as.matrix(m)
m1
set.seed(1)
m_l=1:length(m1)
m_l=m_l[-which(diag(1,nrow = nrow(m1))==1)]
ss=sample(m_l,size = 10)
m1[ss]=1-m1[ss]
m1
对于使用seq.int
而不是diag
n=1000
Unit: microseconds
expr min lq mean median uq max neval
{ which(diag(1, nrow = n) == 1) } 8976.718 9422.967 14397.44991 10489.0520 16001.550 190959.200 100
{ seq(1, by = n + 1, length = n) } 12.941 17.404 37.90449 31.9075 56.004 83.448 100
{ seq.int(1, by = n + 1, length = n) } 5.355 6.248 8.90736 7.1405 12.272 16.512 100
{ 1 + { (1:n) - 1 } * (1 + n) } 5.355 6.248 9.77758 8.9255 11.826 25.437 100