[英]R - Writing individual values in a matrix using matching to create vector of coordinates in R
說我創建一個具有指定行數和列數的0矩陣:
r = 100
c = 100
zero_mat = matrix(rep(0, r*c),r,c)
我還有一個向量,該向量的美國州長為100行,看起來像:
states[1:7,1] #structured as a matrix with 1 column and many rows
California
Arizona
Wisconsin
California
Washington
Washington
Washington
因此,讓我們說我只是將zero_mat的列名稱設為狀態的名稱:
colnames(zero_mat) = t(unique(states))
現在,這是問題。 如何在與狀態所在的行,
states
和與狀態的名稱對應的列的zero_map中的元素中寫入1?
我敢肯定,這只是一行代碼,但是我花了幾個小時試圖弄清楚這沒有用。 我認為這可能有效: zero_mat[1:r, states[1:r,1]] = 1
,但它只返回1的矩陣。
我希望我正確理解了這個問題。 假設這是您的數據:
states = c('Ca', 'Ar', 'Wi', 'Ca', 'Wa', 'Wa', 'Wa')
並且您的zero_mat
及其列名稱的定義如下:
states_uniq = unique(states)
zero_mat = matrix(0, ncol=length(states_uniq), nrow=length(states))
colnames(zero_mat) = states_uniq
## Ca Ar Wi Wa
## [1,] 0 0 0 0
## [2,] 0 0 0 0
## [3,] 0 0 0 0
## [4,] 0 0 0 0
## [5,] 0 0 0 0
## [6,] 0 0 0 0
## [7,] 0 0 0 0
您可以使用match
查找states_uniq
中states
的位置
match(states, states_uniq)
## [1] 1 2 3 1 4 4 4
這些將是您要在zero_mat
設置的1
的列索引。 相應的行索引僅僅是1:length(states)
。 因此,在2列矩陣的行中收集的1
s的行和列索引如下:
cbind(1:length(states), match(states, states_uniq))
## [,1] [,2]
## [1,] 1 1
## [2,] 2 2
## [3,] 3 3
## [4,] 4 1
## [5,] 5 4
## [6,] 6 4
## [7,] 7 4
該2列矩陣可用於索引zero_mat
並將相應的條目設置為1
:
zero_mat[ cbind(1:length(states), match(states, states_uniq)) ] = 1
## Ca Ar Wi Wa
## [1,] 1 0 0 0
## [2,] 0 1 0 0
## [3,] 0 0 1 0
## [4,] 1 0 0 0
## [5,] 0 0 0 1
## [6,] 0 0 0 1
## [7,] 0 0 0 1
如果數據集很大,則可能要使用Matrix
包中的稀疏矩陣來節省空間:
Matrix::sparseMatrix(i=1:length(states),
j=match(states, states_uniq),
x=1,
dimnames=list(NULL, states_uniq))
## 7 x 4 sparse Matrix of class "dgCMatrix"
## Ca Ar Wi Wa
## [1,] 1 . . .
## [2,] . 1 . .
## [3,] . . 1 .
## [4,] 1 . . .
## [5,] . . . 1
## [6,] . . . 1
## [7,] . . . 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.