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.
 
    