30

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.

Community
  • 1
  • 1
Sam Firke
  • 21,571
  • 9
  • 87
  • 105
  • 6
    ... or `unlist(dat[2,])` – Rich Scriven Feb 25 '16 at 03:47
  • Thanks both. Turns out my question stems from not realizing that the product of `mtcars[2, ]` is a `data.frame`, as future operations I do to it like `paste(...)` coerce it to a vector. I mistakenly thought it already was a vector. Now I see I can also `paste(...)` onto a 1-row `tbl_df` and get a vector. With that understanding, I think this is a duplicate. Hope it will at least help others who are thrown off by seeing a `tbl_df`. `unlist(dat[2, ])` is what I went with. – Sam Firke Feb 25 '16 at 04:01

3 Answers3

29

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
Ashirwad
  • 1,890
  • 1
  • 12
  • 14
akrun
  • 874,273
  • 37
  • 540
  • 662
8

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()
Sam Firke
  • 21,571
  • 9
  • 87
  • 105
mk9y
  • 320
  • 2
  • 11
  • `as.numeric` is a nice option! I think the `as_tibble` calls in akrun's answer are just to illustrate how it works on a `tbl_df`, since that was the focus of the question. – Sam Firke Sep 23 '20 at 12:57
0

Wouldn't as.numeric(mtcars[2,]) be the simplest answer?

andrewj
  • 2,965
  • 8
  • 36
  • 37