【问题标题】:How to Add a Unique Identifier to a Dataframe Utilizing the "between" Function in dplyr如何使用 dplyr 中的“between”函数向数据帧添加唯一标识符
【发布时间】:2017-06-22 07:30:32
【问题描述】:

我正在使用 RStudio 中的 MLB Statcast 数据,并试图确定哪些投手最常利用好球区的每个部分。

Statcastplate_x 的形式给出了球越过球门的坐标(球越过本垒时距板中部的左/右距离,以英尺为单位) , 和plate_z(球场在穿过本垒前部时的高度,以英尺为单位)。

例如dataframe:

pitcher_name <- c('AJ Griffin','AJ Griffin','AJ Griffin','AJ Griffin','AJ 
Griffin','AJ Griffin','Adam Conley','Adam Conley','Adam Conley','Adam Conley')

plate_x <- c(0.88, -0.74, 0.54, 0.51, 0.54, 0.49, -0.70, -0.67, 0.78, 0.58)

plate_z <- c(1.63, 1.81, 2.03, 2.60, 1.83, 1.58, 2.82, 2.13, 1.10, 1.72)

strike_zone_analysis <- data.frame(pitcher_name, plate_x, plate_z)

我希望隔离较低的罢工,​​我可以使用 dplyr 中内置的 between 函数来做到这一点:

low_zone <- strike_zone_analysis %>% filter(between(plate_x, -1.01, 1.01), 
                                            between(plate_z, 1.49, 2.17))

我接下来要做的是使用 dplyr 中的 mutate 分配一个唯一标识符(说明低罢工与非低罢工的新列),该标识符适合特定于上述 between 函数的数据点。我的最终目标是使用类似于以下的代码来计算每个投手整体投出的低击球的比例:

P <- pitch_analysis.data %>% 
     group_by(pitcher_name) %>%     
     summarise(r=sum(str_detect(description,"swinging"))/n())

不确定如何组合 dplyr 的函数之间的变异和函数。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:
    strike_zone_analysis %>%
      mutate(low_zone = between(plate_x, -1.01, 1.01) & between(plate_z, 1.49, 2.17)) %>%
      group_by(pitcher_name) %>%
      summarize(low_percent = sum(low_zone)/n())
    

    您可以在 mutate 中组合这两个条件,然后对转换为二进制的逻辑进行分组和求和。

    【讨论】:

      【解决方案2】:

      我猜你在找什么

      strike_zone_analysis %>% 
        group_by(pitcher_name) %>%
        summarize(
          low_strike_per = mean( (plate_x > -1.01 & plate_x < 1.01) & (plate_z > 1.49 & plate_z < 2.17))
        )
      

      【讨论】:

        【解决方案3】:

        我建议将ifelse 语句与mutate 一起使用。如果音高在低区参数之间,则将在新的“low_zone”列中放置 1,否则将输入 0。然后你可以group_by投手和summarise如下。

        strike_zone_analysis %>%
          mutate(low_zone = ifelse(between(plate_x, -1.01, 1.01) & 
                                     between(plate_z, 1.49, 2.17), 1, 0)) %>%
          group_by(pitcher_name) %>%
          summarise(n_of_pitches = n(),
                    prop_low_zone = sum(low_zone)/n_of_pitches)
        
        
        # A tibble: 2 x 3
          pitcher_name n_of_pitches prop_low_zone
                <fctr>        <int>         <dbl>
        1  Adam Conley            4     0.5000000
        2   AJ Griffin            6     0.8333333
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-27
          相关资源
          最近更新 更多