R 替换保持数据结构的矩阵中的值
我有一个矩阵,看起来像这样:R 替换保持数据结构的矩阵中的值,r,R,我有一个矩阵,看起来像这样: [,1] [,2] [1,] 1 4 [2,] 1 3 [3,] 2 4 [4,] 3 4 [5,] 3 6 [6,] 3 5 [7,] 6 7 structure(c(1, 1, 2, 3, 3, 3, 6, 4, 3, 4, 4, 6, 5, 7), .Dim = c(7L, 2L)) 和一个由12000个数字组成的向量: n <- seq_along(1:
[,1] [,2]
[1,] 1 4
[2,] 1 3
[3,] 2 4
[4,] 3 4
[5,] 3 6
[6,] 3 5
[7,] 6 7
structure(c(1, 1, 2, 3, 3, 3, 6, 4, 3, 4, 4, 6, 5, 7), .Dim = c(7L, 2L))
和一个由12000个数字组成的向量:
n <- seq_along(1:12000)
您可以使用
[]
运算符替换矩阵中的所有值,例如:
your_matrix[] = sample(12000, length(your_matrix), replace=FALSE)
your_matrix
# [,1] [,2]
#[1,] 3051 11110
#[2,] 11003 1606
#[3,] 7518 1196
#[4,] 11621 9585
#[5,] 11044 9931
#[6,] 9717 5835
#[7,] 3577 9329
编辑:对不起,我误解了你的问题。要用相同的新值替换相同的旧值,可以使用类似的代码:
# create 1:max_element random values (e.g. 1:7)
s = sample(12000, max(your_matrix), replace=FALSE)
# replace the complete matrix with the random values
# (s[your_matrix] is the same as s[c(1, 1, 2, 3, 3, 3, 6, 4, 3, 4, 4, 6, 5, 7)])
# some values are chosen twice or triple times
m[] = s[your_matrix]
m
# [,1] [,2]
#[1,] 8781 11348
#[2,] 8781 11033
#[3,] 10051 11348
#[4,] 11033 11348
#[5,] 11033 7637
#[6,] 11033 1754
#[7,] 7637 8995
您可以使用
[]
运算符替换矩阵中的所有值,例如:
your_matrix[] = sample(12000, length(your_matrix), replace=FALSE)
your_matrix
# [,1] [,2]
#[1,] 3051 11110
#[2,] 11003 1606
#[3,] 7518 1196
#[4,] 11621 9585
#[5,] 11044 9931
#[6,] 9717 5835
#[7,] 3577 9329
编辑:对不起,我误解了你的问题。要用相同的新值替换相同的旧值,可以使用类似的代码:
# create 1:max_element random values (e.g. 1:7)
s = sample(12000, max(your_matrix), replace=FALSE)
# replace the complete matrix with the random values
# (s[your_matrix] is the same as s[c(1, 1, 2, 3, 3, 3, 6, 4, 3, 4, 4, 6, 5, 7)])
# some values are chosen twice or triple times
m[] = s[your_matrix]
m
# [,1] [,2]
#[1,] 8781 11348
#[2,] 8781 11033
#[3,] 10051 11348
#[4,] 11033 11348
#[5,] 11033 7637
#[6,] 11033 1754
#[7,] 7637 8995
谢谢@sgibb,但是我想保留我的矩阵的内部结构,例如在我的矩阵中
m[1,1]
和m[2,1]
具有相同的值(1
),所以我希望样本矩阵在m[1,1]
,m[2,1]
上保持相同的结构,等等现在它工作得很好,你能给我解释一下密码吗?max
命令告诉要替换的元素的数量,然后按照@user2380782:I添加一些注释的顺序将它们放入矩阵中max
返回矩阵中的最大数,并确保我们的s
获得足够的元素,以便由您的_矩阵
索引。之后,它们会按照矩阵的顺序进行索引。谢谢@sgibb,但我想保留矩阵的内部结构,例如,在我的矩阵中m[1,1]
和m[2,1]
具有相同的值(1
),因此我希望样本矩阵在m[1,1]
上保持相同的结构和相同的值,m[2,1]
等等现在它工作得很好,你能给我解释一下代码吗?max
命令告诉要替换的元素的数量,然后按照@user2380782:I添加一些注释的顺序将它们放入矩阵中max
返回矩阵中的最大数,并确保我们的s
获得足够的元素,以便由您的_矩阵
索引。然后,根据矩阵的顺序对它们进行索引。