替换矩阵保持数据结构中的值
Posted
技术标签:
【中文标题】替换矩阵保持数据结构中的值【英文标题】:Replace values in a matrix keeping data structure 【发布时间】:2014-02-11 06:47:30 【问题描述】:我有一个如下所示的矩阵:
[,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)
我想sample
向量中的值并用它们替换矩阵中的值但保持相同的结构。这是所需输出的两个示例
>example1
[,1] [,2]
[1,] 10 25
[2,] 10 3
[3,] 122 25
[4,] 300 25
[5,] 300 15
[6,] 300 89
[7,] 15 1253
>example2
[,1] [,2]
[1,] 9 2
[2,] 9 30
[3,] 22 2
[4,] 30 2
[5,] 30 5
[6,] 30 58
[7,] 5 253
【问题讨论】:
【参考方案1】:您可以使用[]
运算符来替换矩阵中的所有值,例如:
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]
具有相同的值(@ 987654326@),所以我希望 sample matrix 在m[1,1]
、m[2,1]
等上保持相同的结构和相同的值
现在它工作得很好,你能解释一下代码吗? max
命令告诉要替换的元素的数量,然后按照顺序将它们放入矩阵中??
@user2380782:我添加了一些 cmets。 max
返回矩阵中的最大数,并确保我们的s
获得足够的元素以被your_matrix
索引。然后按矩阵的顺序对它们进行索引。以上是关于替换矩阵保持数据结构中的值的主要内容,如果未能解决你的问题,请参考以下文章
pandas使用replace函数替换dataframe中的值:replace函数对dataframe中指定数据列的值进行替换替换具体数据列的相关值