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?

4
  • 4
    Use colnames instead of names when you have a matrix Commented Oct 13, 2017 at 15:43
  • Why this difference? Commented Oct 13, 2017 at 15:44
  • 2
    Because matrices and data frames are different. Columns aren't as special in matrices as they are in data frames. colnames will work for both. Commented Oct 13, 2017 at 15:46
  • 2
    data.frame is essentially list with properties of matrix in R. You can't expect matrix to be having every method same as data.frame. Commented Oct 13, 2017 at 15:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.