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.
If we want to turn a dataframe row into a character vector then we can use as. character() method In R, we can construct a character vector by enclosing the vector values in double quotation marks, but if we want to create a character vector from data frame row values, we can use the as character function.
Every tibble is a named list of vectors, each of the same length. These vectors form the tibble columns. Take the tibble mpg . Each variable in mpg ( manufacturer , model , displ , etc.) is a vector.
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
From Introduction to dplyr: "All of the dplyr functions take a data frame (or tibble) as the first argument." So no need to convert mtcars
into a tibble. Furthermore, as.numeric()
is more concise than unlist(., use.names = FALSE)
.
library(dplyr) mtcars %>% slice(2) %>% as.numeric()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With