Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the '$' operator do in this R code snippet?

Tags:

r

dplyr

Consider the following R dplyr code:

lahmanNames %>% 
  bind_rows(.id = "dataframe") %>%   # Bind the data frames
  filter(var == "playerID") %>%   # Filter the results
  `$`(dataframe)   #  <---- WHAT DOES $ MEAN?

What does the $ operator refer to in this case?

like image 588
Dirk Avatar asked Mar 08 '26 04:03

Dirk


1 Answers

It is just like doing mtcars$dataframe. there are a bunch of ways to do this. In dplyr 0.7.0 the function pull was added, which does this in a way that works with piping (%>%).


library(dplyr)

mtcars %>% `$`(mpg)

#>  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2
#> [15] 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4
#> [29] 15.8 19.7 15.0 21.4

mtcars$mpg

#>  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2
#> [15] 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4
#> [29] 15.8 19.7 15.0 21.4

mtcars[["mpg"]]

#>  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2
#> [15] 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4
#> [29] 15.8 19.7 15.0 21.4

mtcars %>% pull(mpg)

#>  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2
#> [15] 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4
#> [29] 15.8 19.7 15.0 21.4
like image 84
austensen Avatar answered Mar 09 '26 17:03

austensen