Convert a row of a data frame to vector
I recommend unlist
, which keeps the names.
unlist(df[1,])
a b c
1.0 2.0 2.6
is.vector(unlist(df[1,]))
[1] TRUE
If you don't want a named vector:
unname(unlist(df[1,]))
[1] 1.0 2.0 2.6
When you extract a single row from a data frame you get a one-row data frame. Convert it to a numeric vector:
as.numeric(df[1,])
As @Roland suggests, unlist(df[1,])
will convert the one-row data frame to a numeric vector without dropping the names. Therefore unname(unlist(df[1,]))
is another, slightly more explicit way to get to the same result.
As @Josh comments below, if you have a not-completely-numeric (alphabetic, factor, mixed ...) data frame, you need as.character(df[1,])
instead.
Here is a dplyr
based option:
newV = df %>% slice(1) %>% unlist(use.names = FALSE)
# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()