Bio
Bio

Reputation: 13

transform a matrix to another one using loop

I have a matrix (11x42) and I would like to apply a function for each column one by one and put the result back in a new 11x42 matrix with a new name and modified column names.

I am not used to loops so I am a bit struggling. Here is what I have so far, but not working.

 for (i in 1:ncol(matrix))
  {
    res[[i]] <-residuals(lm(matrix[,i]~HW))
  }

I would like to also use the function paste0("new_", i) to change the names of each column.

Here I was trying to create 42 vectors (res1 to res 42) that I would cbind into a new matrix. But it's not working. And I am pretty sure that could be done within the loop as well.

Thanks in advance!

Upvotes: 1

Views: 40

Answers (1)

Sotos
Sotos

Reputation: 51582

Since its a matrix you should use apply with margin 2, i.e.

new_mat <- apply(your_mat, 2, function(i) residuals(lm(i~HW)))
colnames(new_mat) <- paste0('new_', colnames(your_mat))

Upvotes: 2

Related Questions