R语言 从计数数组创建1矩阵

yeotifhr  于 2023-04-03  发布在  其他
关注(0)|答案(4)|浏览(143)

给定一个长度为6的3个唯一数字的数组,比如:
c(1,1,1,2,3,3)
如何构造下面的6x3矩阵:

[1, 0 , 0]  
[1, 0 , 0]  
[1, 0 , 0]  
[0, 1 , 0]  
[0, 0, 1]  
[0, 0, 1]

一个简单的方法是:

V = c(1,1,1,2,3,3)
Z = matrix(0,6,3)
for (i in 1:6) {Z[i, V[i]] = 1}

但有没有适合这种手术的一次性手术呢

tzdcorbm

tzdcorbm1#

我们可以在base R中使用model.matrix

model.matrix(~ . - 1, data.frame(v1 = factor(v1)))
  • 输出
v11 v12 v13
1   1   0   0
2   1   0   0
3   1   0   0
4   0   1   0
5   0   0   1
6   0   0   1

或使用fastDummies中的dummy_cols

library(fastDummies)
dummy_cols(v1)[-1]
  .data_1 .data_2 .data_3
1       1       0       0
2       1       0       0
3       1       0       0
4       0       1       0
5       0       0       1
6       0       0       1

数据

v1 <- c(1,1,1,2,3,3)
tjrkku2a

tjrkku2a2#

使用moderr:

library(modelr)
V = c(1,1,1,2,3,3)
V <- factor(V)
Z <- as.matrix(model_matrix(V , ~ V -1))
Z
    V1 V2 V3
[1,]  1  0  0
[2,]  1  0  0
[3,]  1  0  0
[4,]  0  1  0
[5,]  0  0  1
[6,]  0  0  1
sz81bmfz

sz81bmfz3#

尝试outer

V = c(1,1,1,2,3,3)
+outer(V, unique(V), `==`)
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    1    0    0
## [3,]    1    0    0
## [4,]    0    1    0
## [5,]    0    0    1
## [6,]    0    0    1
bjg7j2ky

bjg7j2ky4#

我们可以vapply a tablulate

t(vapply(v1, \(x) tabulate(x, max(v1)), numeric(max(v1))))
#      [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    1    0    0
# [3,]    1    0    0
# [4,]    0    1    0
# [5,]    0    0    1
# [6,]    0    0    1
  • 数据:*
v1 <- c(1, 1, 1, 2, 3, 3)

相关问题