我有4个种群的样本量矢量:3 2 1 4,总计10个人。我需要动态的代码(因此可以在不同的情况下使用)制作一个1和0的矩阵,其中10行和4列具有3 1,然后该列的其余部分为0,然后下一列有3 0然后2 1然后剩下的0,依此类推如下:
1 0 0 0
1 0 0 0
1 0 0 0
0 1 0 0
0 1 0 0
0 0 1 0
0 0 0 1
0 0 0 1
0 0 0 1
0 0 0 1
输入:
nSamples <- c(3,2,1,4)
答案 0 :(得分:3)
这是一个可能的两步法。
# create a matrix of zeros first
m <- matrix(0L, ncol = length(nSamples), nrow = sum(nSamples))
# then replace relevant 0s with 1s:
m[cbind(1:nrow(m), rep(seq_along(nSamples), nSamples))] <- 1L
m
# [,1] [,2] [,3] [,4]
# [1,] 1 0 0 0
# [2,] 1 0 0 0
# [3,] 1 0 0 0
# [4,] 0 1 0 0
# [5,] 0 1 0 0
# [6,] 0 0 1 0
# [7,] 0 0 0 1
# [8,] 0 0 0 1
# [9,] 0 0 0 1
# [10,] 0 0 0 1
&#34;技巧&#34;,如果你愿意,
rep(seq_along(nSamples), nSamples)
#[1] 1 1 1 2 2 3 4 4 4 4
答案 1 :(得分:1)
您可以使用model.matrix
f_nSamples <- factor(rep(nSamples, nSamples), orderd=TRUE)
model.matrix(~f_nSamples-1)
## f_nSamples1 f_nSamples2 f_nSamples3 f_nSamples4
## 1 1 0 0 0
## 2 1 0 0 0
## 3 1 0 0 0
## 4 0 1 0 0
## 5 0 1 0 0
## 6 0 0 1 0
## 7 0 0 0 1
## 8 0 0 0 1
## 9 0 0 0 1
## 10 0 0 0 1
## attr(,"assign")
## [1] 1 1 1 1
## attr(,"contrasts")
## attr(,"contrasts")$f_nSamples
## [1] "contr.treatment"
答案 2 :(得分:1)
以下是sparseMatrix
library(Matrix)
m1 <- sparseMatrix(i = seq(sum(nSamples)), j = rep(seq_along(nSamples), nSamples), x = 1)
as.matrix(m1)
# [,1] [,2] [,3] [,4]
#[1,] 1 0 0 0
#[2,] 1 0 0 0
#[3,] 1 0 0 0
#[4,] 0 1 0 0
#[5,] 0 1 0 0
#[6,] 0 0 1 0
#[7,] 0 0 0 1
#[8,] 0 0 0 1
#[9,] 0 0 0 1
#[10,] 0 0 0 1