Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing row-values in matrix by its row index

I use a r-matrix (for example [[0,0,0,1],[0,1,0,1],[1,0,0,0],[0,0,1,1]]) representing a raster. I'd like to replace every value except 0 with its row index value. Is there something like

matrix[matrix==1] <- row_index

so that my result would look like [[0,0,0,1],[0,2,0,2],[3,0,0,0],[0,0,4,4]]?

I am using R 2.15.1 on a Mac (10.7.5) and RPY2 2.2.6 to start the R-Methods. Or is there any other way to get reasonable results for statistical functions like histogram, chi_square etc.?

like image 434
user2132627 Avatar asked Dec 11 '25 07:12

user2132627


1 Answers

For a succinct, expressive solution, I'd be likely to use this:

m <- matrix(c(0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1), 
            nrow = 4, byrow = TRUE)

m[m!=0] <- row(m)[m!=0]
m
#      [,1] [,2] [,3] [,4]
# [1,]    0    0    0    1
# [2,]    0    2    0    2
# [3,]    3    0    0    0
# [4,]    0    0    4    4
like image 75
Josh O'Brien Avatar answered Dec 13 '25 20:12

Josh O'Brien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!