我希望我能正确理解这个问题。假设这是您的数据:
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 在states_uniq 中的位置
match(states, states_uniq)
## [1] 1 2 3 1 4 4 4
这些将是您要在zero_mat 中设置的1s 的列索引。相应的行索引只是1:length(states)。所以你的1s 的行和列索引,收集在一个 2 列矩阵的行中如下:
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