0

within R, I create a matrix

m = matrix(c(1,2,3,4),ncol=2)

then I take just the first column using this syntax:

col1 = m[,1]

This gives me the values from the first column, but col1 is of type "numeric" instead of matrix.

I can convert it back to a matrix by doing:

as.matrix(col1, ncol=1)

but it seems like there's gotta be a better way (a shorter way to initialize a matrix inline as well -- e.g. [[1,3],[2,4]] -- or something.

Any pointers to good reference / ways to learn R basics would be appreciated as well.

Kem Mason
  • 1,548
  • 17
  • 26
  • Are you looking for `m[, 1, drop = F]`? By default, `[` will coerce the resulting object to the lowest possible dimension (a `numeric` vector in your case). `drop = FALSE` prevents this conversion. See `help("[")` for details. – Maurits Evers Jan 25 '19 at 01:32
  • yeh that works -- it's not quite as clean / short as I was hoping for, but I can make my own function using that parameter easily enough -- thanks for the suggestion -- if you make it an answer, I'll accept. – Kem Mason Jan 25 '19 at 01:56
  • Your question was actually closed as a dupe, so no need for an independent answer. You can find more interesting information if you follow the dupe target link at the top. If you're working with a `data.frame` (instead of a `matrix`), `dplyr::select` avoids the automatic coercion. Compare e.g. `mtcars[, 1]` vs. `library(dplyr); mtcars %>% select(1)`. – Maurits Evers Jan 25 '19 at 02:02
  • nice, thanks much for your help :) – Kem Mason Jan 25 '19 at 02:49

0 Answers0