【问题标题】:Converting dplyr chain to function将 dplyr 链转换为函数
【发布时间】:2021-07-22 00:48:15
【问题描述】:

嗨,我只是想弄清楚如何将 dplyr 链转换为 R 中的函数。因此位置和速度变量具有三个潜在值。对于位置:“rb”、“wr”、“te”。对于速度,它是:“快”、“中”、“慢”。我的表头是这样的:

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                

我正在尝试创建一个函数,该函数允许我找到一个位置的总码数中速度(例如中速)的比例。我知道如何在 dplyr 中做到这一点。这给了我正确的答案:

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

无论如何我可以把它放到一个函数中,在那里我可以输入位置和速度并获得正确的比例?当我的意思是我想输入位置或速度时,我的意思是能够将例如“wr”和“medium”放入一个函数中,并在“wr”位置获得中速球员的码数比例。谢谢

【问题讨论】:

  • 您能详细说明一下您希望“输入位置和速度并获得正确的比例”的样子吗? [请编辑问题以添加此内容。]
  • 仅供参考,您的汇总统计数据并未反映此示例数据提供的内容。
  • 嗨。因此位置和速度变量具有三个潜在值。对于位置:“rb”、“wr”、“te”。对于速度,它是:“快”、“中”、“慢”。当我的意思是我想输入位置或速度时,我的意思是能够将例如“wr”和“medium”放入一个函数中,并在“wr”位置获得中速球员的码数比例
  • @r2evans 正确。这不是上面的完整表格。只是其中的一部分

标签: r function dplyr tidyverse


【解决方案1】:

这有帮助吗?

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 }})
}

试试看:

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

有关“curly curly”运算符的更多信息,我建议查看https://www.tidyverse.org/blog/2019/06/rlang-0-4-0/https://sharla.party/post/tidyeval/

【讨论】:

    猜你喜欢
    • 2020-02-06
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2021-08-08
    相关资源
    最近更新 更多