R Vectorize:为每一行分配值,diff col基于每行的col索引
R Vectorize: Assign values to each row, diff col based on col index for every row
我有一个包含 40000 行和 9 列的 A 矩阵和一个包含 40000 个项目的向量 B。
B 中的每个项目都是从 1 到 9 的数字。我想将 A 中与 B 中的项目对应的特定列分配为 1。
现在,我正在为它使用 for 循环。
for(r in 1:40000){
A[r,B[r]]=1
}
但是有没有办法对其进行矢量化?
谢谢
你可以试试
A[cbind(1:nrow(A), B)] <- 1
使用 OP 的代码检查结果
for(r in 1:nrow(A1)){
A1[r, B[r]] <- 1
}
identical(A, A1)
#[1] TRUE
这里我们使用我们用 cbind
创建的矩阵。来自 ?"["
:
When indexing arrays by [ a single argument i can be a matrix with as many columns as there are dimensions of x; the result is then a vector with elements corresponding to the sets of indices in each row of i.
数据
set.seed(24)
A <- matrix(sample(1:40, 25*9, replace=TRUE), ncol=9)
B <- sample(1:9, 25, replace=TRUE)
A1 <- A
我有一个包含 40000 行和 9 列的 A 矩阵和一个包含 40000 个项目的向量 B。 B 中的每个项目都是从 1 到 9 的数字。我想将 A 中与 B 中的项目对应的特定列分配为 1。 现在,我正在为它使用 for 循环。
for(r in 1:40000){
A[r,B[r]]=1
}
但是有没有办法对其进行矢量化? 谢谢
你可以试试
A[cbind(1:nrow(A), B)] <- 1
使用 OP 的代码检查结果
for(r in 1:nrow(A1)){
A1[r, B[r]] <- 1
}
identical(A, A1)
#[1] TRUE
这里我们使用我们用 cbind
创建的矩阵。来自 ?"["
:
When indexing arrays by [ a single argument i can be a matrix with as many columns as there are dimensions of x; the result is then a vector with elements corresponding to the sets of indices in each row of i.
数据
set.seed(24)
A <- matrix(sample(1:40, 25*9, replace=TRUE), ncol=9)
B <- sample(1:9, 25, replace=TRUE)
A1 <- A