Convert a row of a data frame to vector
I want to create a vector out of a row of a data frame. But I don't want to have to row and column names. I tried several things... but had no luck.
This is my data frame:
> df <- data.frame(a=c(1,2,4,2),b=c(2,6,2,1),c=c(2.6,8.2,7.5,3))
> df
a b c
1 1 2 2.6
2 2 6 8.2
3 4 2 7.5
4 2 1 3.0
I tried:
> newV <- as.vector(df[1,])
> newV
a b c
1 1 2 2.6
But I really want something looking like this:
> newV <- c( 1,2,2.6)
> newV
[1] 1.0 2.0 2.6
Solution 1:
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.
Solution 2:
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
Solution 3:
Here is a dplyr
based option:
newV = df %>% slice(1) %>% unlist(use.names = FALSE)
# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()
Solution 4:
If you don't want to change to numeric you can try this.
> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6