Chives M
Chives M

Reputation: 25

Converting dplyr chain to function

Hi so I am just trying to figure out how to convert a dplyr chain into a function in R. So the position and speed variables have three potential values. For position: "rb", "wr", "te". For speed it's: "fast", "medium", "slow". The head of my table looks like this:

position       speed          yards 
   rb          fast            805                 
   wr          slow            924                 
   rb          medium          503 
   te          fast            803 
   wr          medium          1002 
   rb          fast            920   
   te          slow            530  
   rb          fast            920  
   wr          slow            920                

I'm trying to create a function that allows me to find the proportion of speed (for example medium) out of a positions' total yards. I know how to do it in dplyr. This gives me the correct answer:

df %>%    
  group_by(position, speed) %>%
  summarise(yards = sum(yards)) %>%
  group_by(position) %>%
  mutate(freq = yards / sum(yards))
  position speed  yards  freq
1 rb       fast    1729 0.200
2 rb       medium  4741 0.547
3 rb       slow    2196 0.253

Is there anyway I can put this into a function where I can input the position and the speed and get the correct proportion? When I mean I want to input the position or speed, I mean being able to just put in for example "wr" and "medium" into a function and getting the proportion of yards by medium speed players at position "wr". Thank you

Upvotes: 1

Views: 53

Answers (1)

Jon Spring
Jon Spring

Reputation: 66935

Does this help?

lookup_func <- function(homeworld, species) {

  # You could keep this part outside of the function if you just want to calc once
  my_lookup_table <- dplyr::starwars %>%
    group_by(homeworld, species) %>%
    summarise(across(where(is.numeric), mean), .groups = "drop")
  
  # Here we filter using the input text and the "curly curly" or "embrace" operator
  #   in "tidyeval" that serves to transport the input into
  #   the context of the function.
  my_lookup_table %>%
    filter(homeworld == {{ homeworld }},
           species   == {{ species }})
}

Try it out:

lookup_func("Tatooine", "Human")

# A tibble: 1 x 5
  homeworld species height  mass birth_year
  <chr>     <chr>    <dbl> <dbl>      <dbl>
1 Tatooine  Human     179.    NA       47.5

For more on the "curly curly" operator, I suggest looking at https://www.tidyverse.org/blog/2019/06/rlang-0-4-0/ and https://sharla.party/post/tidyeval/

Upvotes: 1

Related Questions