2014-01-21 39 views
0

我有一個矩陣,看起來像這樣:在矩陣中保持數據結構替換值

 [,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 

回答

4

你可以使用[]運營商,以取代矩陣中的所有值,例如:

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 
+0

感謝@sgibb,但我想保持我的矩陣_internal structure_,例如在我的矩陣'M [1 ,1]'和'm [2,1]'具有相同的值('1'),所以我希望_sample matrix_保持與'm [1,1]'相同的結構, m [2,1]'等等 – user2380782

+0

@ user2380782:請參閱我的編輯。 – sgibb

+0

現在它工作完美,你能解釋一下我的代碼嗎? 'max'命令告訴要替換的元素的數量,然後將它們放在矩陣中,按照順序? – user2380782