Phani
Phani

Reputation: 3325

Why does reordering turn single column data frames into vectors?

I am just curious why reordering a single columned data frame (or matrix) converts it into a vector. Is there any reason for this?

k <- data.frame(a=c(2,10,3), b=c(8,3,9))
k <- k[order(k[,1]),]
class(k)
# [1] "data.frame"

k <- data.frame(a=c(2,10,3))
k <- k[order(k[,1]),]
class(k)
# [1] "numeric"

Upvotes: 0

Views: 74

Answers (1)

csgillespie
csgillespie

Reputation: 60492

Look at ?'[' In particular, the drop argument

drop: For matrices and arrays.  If ‘TRUE’ the result is coerced to
      the lowest possible dimension (see the examples).  This only
      works for extracting elements, not for the replacement.  See
      ‘drop’ for further details.

To answer your question, you want

k[order(k[,1]), , drop=FALSE]

Upvotes: 4

Related Questions