Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a single dplyr tbl_df row as a vector

Tags:

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.

like image 451
Sam Firke Avatar asked Feb 25 '16 03:02

Sam Firke


People also ask

How do I turn a row into a vector in R?

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.

Is a Tibble a vector?

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.


2 Answers

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 
like image 120
akrun Avatar answered Sep 22 '22 01:09

akrun


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() 
like image 23
mk9y Avatar answered Sep 21 '22 01:09

mk9y