Search code examples
rmatrixmatrix-indexing

R programming: How to do replace values by row?


How to do a row-wise replacement of values using R? I have a Matrix and I would like to replace some of its values using an index vector. The problem is that R automatically does a column-wise extraction of the values as opposed to a row-wise. You will find my code and results below:

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

What I actually want to get is the row-wise version of this meaning:

     [,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
> 

Apparently R does a column-wise replacement of values by default. What is the best way to obtain a row-wise replacement of the values?

Thanks!


Solution

  • You could recalculate the onedimensional indizes to row- and column-indices. Supposing you have calculated the row-indices in the first column of the matrix Ind and the columnindices in the second column of Ind you can do 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