1

I want to drop columns by name in a matrix, I noticed that it does not work the same as for data frame:

df <- as.matrix(data.frame(x=1:5, y=2:6, z=3:7, u=4:8))

df[ , -which(names(df) %in% c("z","u"))]


df <- data.frame(x=1:5, y=2:6, z=3:7, u=4:8)

df[ , -which(names(df) %in% c("z","u"))]

Why and how can I fix this?

Al14
  • 1,734
  • 6
  • 32
  • 55

1 Answers1

1

With a matrix you can use colnames or rownames (or, if you need to generalize up to an array with more dimensions, the dimnames list).

names isn't defined for a matrix. It is defined for a list, and thus for a data.frame, where columns are generally more important (in some sense, at least), so it is a safe convention that names refers to column names. But in an array there is no reason to prefer one dimension to another.

A similar question is Extract matrix column values by matrix column name.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294