0
votes

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.

1
Please provide example input and expected output.zx8754
So, you have a data.frame with row and column indices and the values? And you want to reshape it into a matrix?Roland
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

1 Answers

-1
votes

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.