Question

I am trying to assign the values from the dataframe into a matrix. The columns 2 and 3 are mapped to rows and columns respectively in the matrix. This is not working since the sim.mat is not storing the values.

score <- function(x, sim.mat) {
  r <- as.numeric(x[2])
  c <- as.numeric(x[3])
  sim.mat[r,c] <- as.numeric(x[4])
}


mat <- apply(sim.data, 1, score, sim.mat)

Is this the right approach? If yes how can I get it to work.

Was it helpful?

Solution

No need for apply, try this:

score <- function(x, sim.mat) {
  r <- as.numeric(x[[2]])
  c <- as.numeric(x[[3]])
  sim.mat[cbind(r,c)] <- as.numeric(x[[4]])
  sim.mat
}

mat <- score(sim.data, sim.mat)

Check the "Matrices and arrays" section of ?"[" for documentation.


If you really wanted to use apply like you did, you would need your function to modify sim.data in the calling environment, do:

score <- function(x, sim.mat) {
   r <- as.numeric(x[2])
   c <- as.numeric(x[3])
   sim.mat[r,c] <<- as.numeric(x[4])
}

apply(sim.data, 1, score, sim.mat)
sim.mat

This type of programming where functions have side-effects is really not recommended.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top