R 编程:如何按行替换值?

R programming: How to do replace values by row?

如何使用 R 对值进行逐行替换? 我有一个矩阵,我想用索引向量替换它的一些值。问题是 R 会自动按列提取值,而不是按行提取值。 您将在下面找到我的代码和结果:

Matrix=matrix(rep(0,42),nrow=6,ncol=7,byrow=TRUE)
v=c(1,7,11,16,18)
Matrix[v]=1
Matrix
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    1    0    0    0    0    0
[2,]    0    0    0    0    0    0    0
[3,]    0    0    0    0    0    0    0
[4,]    0    0    1    0    0    0    0
[5,]    0    1    0    0    0    0    0
[6,]    0    0    1    0    0    0    0

我真正想要得到的是这个意思的逐行版本:

     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    0    0    0    0    0    1
[2,]    0    0    0    1    0    0    0
[3,]    0    1    0    1    0    0    0
[4,]    0    0    0    0    0    0    0
[5,]    0    0    0    0    0    0    0
[6,]    0    0    0    0    0    0    0
> 

显然 R 默认情况下会按列替换值。 获取值的逐行替换的最佳方法是什么?

谢谢!

您可以重做 1 以使它们按行排列,或者您可以执行以下操作:

Matrix=matrix(rep(0,42),nrow=6,ncol=7,byrow=TRUE)
v=c(1,7,11,16,18)
Matrix<-t(Matrix)
Matrix[v]=1
Matrix<-t(Matrix)
Matrix

     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    0    0    0    0    0    1
[2,]    0    0    0    1    0    0    0
[3,]    0    1    0    1    0    0    0
[4,]    0    0    0    0    0    0    0
[5,]    0    0    0    0    0    0    0
[6,]    0    0    0    0    0    0    0

您可以将一维索引重新计算为行索引和列索引。假设您已经计算了矩阵 Ind 第一列中的行索引和 Ind 第二列中的列索引,您可以执行 Matrix[Ind] <- 1

Matrix <- matrix(rep(0,42),nrow=6,ncol=7,byrow=TRUE)
v <- c(1,7,11,16,18)
Row <- (v-1) %/% ncol(Matrix) +1
Col <- (v-1) %% ncol(Matrix) +1
Matrix[cbind(Row,Col)] <- 1
Matrix
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,]    1    0    0    0    0    0    1
# [2,]    0    0    0    1    0    0    0
# [3,]    0    1    0    1    0    0    0
# [4,]    0    0    0    0    0    0    0
# [5,]    0    0    0    0    0    0    0
# [6,]    0    0    0    0    0    0    0

我们可以做到

+(matrix(seq_along(Matrix) %in% v, ncol=ncol(Matrix), nrow=nrow(Matrix), byrow=TRUE))
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#[1,]    1    0    0    0    0    0    1
#[2,]    0    0    0    1    0    0    0
#[3,]    0    1    0    1    0    0    0
#[4,]    0    0    0    0    0    0    0
#[5,]    0    0    0    0    0    0    0
#[6,]    0    0    0    0    0    0    0