0

I have a matrix with 50 rows and 50 columns:

[,1] [,2] [,3]...[,50]
[1,]    1    0.8    0.7
[2,]    0.8    1    0.5
[3,]    0.7    0.5    1
...
[50,]

And I want to sum 0.02 in values up to diagonal to obtain something like this:

[,1] [,2] [,3]...[,50]
[1,]    1    0.82    0.72
[2,]    0.8    1    0.52
[3,]    0.7    0.5    1
...
[50,]

Does anyone know how the sum could be done only in the values that are above the diagonal of the matrix using R?

Example of matrix code:

matrix <- as.matrix(data.frame(A = c(1, 0.8, 0.7), B = c(0.8, 1, 0.5), C = c(0.7, 0.5, 1)), nrow=3, ncol=3)
  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Avoid "..." in examples because then we can't copy/paste for testing. Also you don't need all 50 columns and rows for testing. Just make a nice complete matrix with just a few rows. – MrFlick May 19 '21 at 08:42
  • 3
    Besides, take a look at `?upper.tri` – markus May 19 '21 at 08:44

2 Answers2

4

Try upper.tri like below

matrix[upper.tri(matrix)] <- matrix[upper.tri(matrix)] + 0.02
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
2

You can use lower.tri(m) or upper.tri(m) functions in R. Which m is your matrix.

m = matrix(1:36, 6, 6)
m[upper.tri(m)] = m[upper.tri(m)] + 0.02
m
Beril Boga
  • 97
  • 2
  • 9