'Extract a single dplyr tbl_df row as a vector
How can one extract a single row from a tbl_df as a vector? Simple subsetting with [] brackets yields a 1-row tbl_df:
library(dplyr)
dat <- as_data_frame(mtcars)
dat[2, ]
Source: local data frame [1 x 11]
mpg cyl disp hp drat wt qsec vs am gear carb
(dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl)
1 21 6 160 110 3.9 2.875 17.02 0 1 4 4
A similar problem to Extract a dplyr tbl column as a vector, but with (I think) some different solutions.
Solution 1:[1]
Using the dplyr %>% operator
library(dplyr)
as_tibble(mtcars) %>%
slice(2) %>%
unlist(., use.names=FALSE)
Or we can use c with recursive=TRUE
as_tibble(mtcars) %>%
slice(2) %>%
c(., recursive=TRUE) %>%
unname
Solution 2:[2]
Wouldn't
as.numeric(mtcars[2,])
be the simplest answer?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ashirwad |
| Solution 2 | andrewj |
