3
mtcars %>% select(mpg) %>% class()
[1] "data.frame"

Is not the same as:

x <- mtcars %>% select(mpg)
x$mpg %>% class
[1] "numeric"

I have a dplyr chain with several operations. In the end I need the actual content of df$feature, not a data frame with one feature.

Doesn't work:

 mtcars %>% select(mpg)$mpg
Error in .$select(mpg) : 3 arguments passed to '$' which requires 2

Is there a way to get the numeric vector mpg within a dplyr chain? So that I don't have to create a variable defined by the dplyr chain, then a new variable df$x like a above. Is it possible to do it in a oner?

Doug Fir
  • 19,971
  • 47
  • 169
  • 299

2 Answers2

4

Here, select always returns a data.frame with the columns selected even if it is a single column. The class would be obviously data.frame if we are not extracting the column. Instead, we can use pull to extract the column as a vector and now the class would be the class of the column/vector

library(dplyr)
mtcars %>% 
    pull(mpg) %>% 
    class
#[1] "numeric"

If we use the select approach, then the column can be extracted with $ or .[[

mtcars %>% 
    select(mpg) %>%
    .$mpg
    #or 
    #.[["mpg"]]

The . represents the whole dataset

Or using extract2 from magrittr

mtcars %>%
     select(mpg) %>% 
     magrittr::extract2('mpg')

Or other options include unlist or flatten_dbl

mtcars %>% 
    select(mpg) %>% 
    flatten_dbl
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Alternatively to pull, you can use unlist to transform the selected column of your data.frame into a vector:

mtcars %>% select(mpg) %>% unlist() %>% class

[1] "numeric"
dc37
  • 15,840
  • 4
  • 15
  • 32