从 r 中的向量创建一个复杂的矩阵
Create a complicated matrix from vector in r
我有 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)
您可以使用 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"
这是一种可能的两步法。
# 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
如果你愿意,"trick" 是
rep(seq_along(nSamples), nSamples)
#[1] 1 1 1 2 2 3 4 4 4 4
这里是单行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
我有 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)
您可以使用 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"
这是一种可能的两步法。
# 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
如果你愿意,"trick" 是
rep(seq_along(nSamples), nSamples)
#[1] 1 1 1 2 2 3 4 4 4 4
这里是单行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