【问题标题】:Expand Grid for only certain parts of a datafame仅为数据框的某些部分展开网格
【发布时间】:2022-12-31 03:14:12
【问题描述】:

我在 R 中有一个数据框,如下所示:

head(pitch_type_df)
# A tibble: 6 x 20
# Groups:   player_name, pitcher [3]
  player_name pitcher pitch~1 relea~2 relea~3 pfx_x~4  pfx_z relea~5 relea~6 relea~7 spin_~8 spin_~9 velo_~*
  <chr>         <dbl> <chr>     <dbl>   <dbl>   <dbl>  <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>
1 Abbott, Co~  676265 FF         91.3   2253. -0.959   1.43    -2.60    5.48    6.27   0.837   219.     0   
2 Abbott, Co~  676265 KC         84.4   2291.  0.0784 -0.459   -2.48    5.85    6.01   0.220    39.9   -6.93
3 Abbott, Co~  676265 SL         86.6   2133. -0.852   0.486   -2.47    5.88    6.06   0.390   225.    -4.85
4 Abreu, Alb~  656061 SI         98.5   2200. -1.22    1.10    -1.71    5.69    6.62   0.874   220.     0   
5 Abreu, Alb~  656061 SL         88.6   2265.  0.209   0.457   -2.05    5.74    6.43   0.145   190.    -9.76

我想实现一些方法来使用 expand_grid 添加两列 plate_x 和 plate_z,它们分别是从 -1.75 到 1.75 和 0 到 4.5 的序列。我如何才能将它添加到我的数据框中,即根据排序的值创建一个网格,以获得每行包含 plate_x 和 plate_z 的所有唯一组合的数据框,而无需将具有所有其他列的唯一组合的网格放在一起?与每一行的原始网格相结合的网格如下所示:

expand_grid(plate_x = seq(-1.75, 1.75, by = .1), plate_z = seq(0, 4.25, by = .1))
# A tibble: 1,548 x 2
   plate_x plate_z
     <dbl>   <dbl>
 1   -1.75     0  
 2   -1.75     0.1
 3   -1.75     0.2
 4   -1.75     0.3
 5   -1.75     0.4
 6   -1.75     0.5
 7   -1.75     0.6
 8   -1.75     0.7
 9   -1.75     0.8
10   -1.75     0.9
# ... with 1,538 more rows
# i Use `print(n = ...)` to see more rows

对于每一行,我的最终产品将是添加到该网格的第一个数据框中的每一行。

【问题讨论】:

    标签: r tidyr data-wrangling


    【解决方案1】:

    我们可以使用crossing

    library(tidyr)
    crossing(pitch_type_df,
        expand_grid(plate_x = seq(-1.75, 1.75, by = .1), 
        plate_z = seq(0, 4.25, by = .1)))
    

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 2011-04-12
      相关资源
      最近更新 更多