2

I know how to remove columns by name from R dataframe, but I can not figure out how to do it in matrix. I want to do something like this:

> m <- matrix(1:6, nrow=2, ncol = 3)
> colnames(m) <- c("q", "w", "e")
> m
     q w e
[1,] 1 3 5
[2,] 2 4 6
> variable_to_remove <- "q"
> m[,variable_to_remove] <- NULL
Error in m[, variable_to_remove] <- NULL : 
number of items to replace is not a multiple of replacement length

The important thing is that I need to use "variable_to_remove", which is a string. After some time, I found that subset() does it:

> subset(m, select=-c(get(variable_to_remove)))
     w e
[1,] 3 5
[2,] 4 6

I really do not like to play with functions like get(), eval(), parse() etc. Is there some simpler and nicer way to do it?

Moysey Abramowitz
  • 352
  • 1
  • 7
  • 19

0 Answers0