[R] data.frame into vector

Marc Schwartz MSchwartz at MedAnalytics.com
Tue Nov 23 19:04:17 CET 2004

On Tue, 2004-11-23 at 16:27 +0000, Tiago R Magalhaes wrote:
> Hi
> I want to extract a row from a data.frame but I want that object to 
> be a vector . After trying some different ways I end up always with a 
> data.frame or with the wrong vector. Any pointers?
>   x <- data.frame(a = factor(c('a',2,'b')), b = c(4,5,6))
> I want to get
> "a" "4"
> I tried:
> as.vector(x[1,])
>    a b
> 1 a 4
> (resulting in a data.frame even after in my mind having coerced it 
> into a vector!)
> as.vector(c[1,], numeric='character')
> [1] "2" "4"
> (almost what I want, except that "2" instead of "a" - I guess this as 
> to do with levels and factors)
> Thanks for any help

Part of the problem that you are having, as you seem to pick up, is that
the first column in 'x' is a factor and you need to coerce it to a

If you review the help for as.matrix, you will note in the details

"as.matrix is a generic function. The method for data frames will
convert any non-numeric/complex column into a character vector using
format and so return a character matrix, except that all-logical data
frames will be coerced to a logical matrix."

Thus, one approach is:

> as.matrix(x)[1, ]
  a   b
"a" "4"

This coerces the data frame to a character matrix, which is then
subsetted to the first row only.


Marc Schwartz

More information about the R-help mailing list