0

I have a predefined matrix M = matrix(0,5,4) . I want to update the matrix elements from value zero to proper value basis the value of the dataframe df object as per condition df$colA = x (matrix row element) and df$colB = y (matrix column element). I have set the row names and col names with the respective unique colA and colB values. ColA and ColB values are discrete integers instead of taking regular sequence values.

M=matrix(0,5,4) rownames(M)=c(135,138,145,146,151) colnames(M)=c(192,204,206,207)

    192 204 206 207
135   0   0   0   0
138   0   0   0   0
145   0   0   0   0
146   0   0   0   0
151   0   0   0   0

df-> ColA   ColB    ColC
135 192 1
135 204 1
135 206 -1
138 192 -1
138 206 1
138 207 1
145 192 -1
145 204 -1
145 206 -1
145 207 1
146 206 1
146 207 1
151 192 -1
151 207 1
for (r in rownames(M)) {
  for (c in colnames(M)) {
    tmp = df[(df$colA == c & df$colB==r),]$colC
    if (!(length(tmp) == 0)) {
      M[(rownames(M) == r),(colnames(M) == c)]= tmp
    }
  }
}

Instead of using for loop, wondering if this can be achieved with an apply or outer function with the matric updation part being handled using a custom function. Please help how to achieve this.

I was trying to refer to this link, but no luck.

mbansal
  • 1
  • 2
  • 1
    Please provide [example input](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and expected output. – zx8754 Nov 13 '17 at 13:36
  • So, you have a data.frame with row and column indices and the values? And you want to reshape it into a matrix? – Roland Nov 13 '17 at 14:30
  • I have provided the example data set, I want to update the matrix elements with 1 or -1 which have matching col values in the data frames but if not then leave it with initial value of 0. – mbansal Nov 14 '17 at 11:58

1 Answers1

-1

To modify a matrix, you can use apply() function. The code will be:

apply(M,1,function(x) <your_function>) # If you want to run for each row
apply(M,2,function(x) <your function>) # If you want to run for each column

If you write the function you want or a short example, we will offer you a better help.

R18
  • 1,476
  • 1
  • 8
  • 17
  • want to edit each element of the matrix at the same time; instead of passing 1 or 2 one can also pass them together as c(1,2) right. So, tried something like apply(M,c(1,2), my_func) but no luck, may be not able to pass the parameter properly or define the function parameter. Need help on this. – mbansal Nov 14 '17 at 11:28