Как объединить несколько переменных и создать новый набор данных? - PullRequest
0 голосов
/ 16 апреля 2020

https://www.kaggle.com/nowke9/ipldata ----- Содержит данные IPL.

Это предварительное исследование, выполненное для набора данных IPL. (ссылка на данные прикреплена выше) После слияния обоих файлов с "id" и "match_id" я создал еще четыре переменные, а именно total_extras, total_runs_scored, total_fours_hit и total_sixes_hit. Теперь я буду sh объединять эти вновь созданные переменные в один фрейм данных. Когда я назначаю эти переменные в одну переменную, а именно batsman_aggregate и выбираю только необходимые столбцы, я получаю сообщение об ошибке.

    library(tidyverse)
    deliveries_tbl <- read.csv("deliveries_edit.csv")
    matches_tbl <- read.csv("matches.csv")

    combined_matches_deliveries_tbl <- deliveries_tbl %>%
    left_join(matches_tbl, by = c("match_id" = "id"))

    # Add team score and team extra columns for each match, each inning.
    total_score_extras_combined <- combined_matches_deliveries_tbl%>%
    group_by(id, inning, date, batting_team, bowling_team, winner)%>%
    mutate(total_score = sum(total_runs, na.rm = TRUE))%>%
    mutate(total_extras = sum(extra_runs, na.rm = TRUE))%>%
    group_by(total_score, total_extras, id, inning, date, batting_team, bowling_team, winner)%>%
    select(id, inning, total_score, total_extras, date, batting_team, bowling_team, winner)%>%
    distinct(total_score, total_extras)%>%
    glimpse()%>%
    ungroup()


# Batsman Aggregate (Runs Balls, fours, six , Sr)
# Batsman score in each match
batsman_score_in_a_match <- combined_matches_deliveries_tbl %>%
    group_by(id, inning, batting_team, batsman)%>%
    mutate(total_batsman_runs = sum(batsman_runs, na.rm = TRUE))%>%
    distinct(total_batsman_runs)%>%
    glimpse()%>%
        ungroup()

# Number of deliveries played . 
balls_faced <- combined_matches_deliveries_tbl %>%
    filter(wide_runs == 0)%>%
    group_by(id, inning, batsman)%>%
    summarise(deliveries_played = n())%>%
    ungroup()

# Number of 4 and 6s by a batsman in each match.
fours_hit <- combined_matches_deliveries_tbl %>%
    filter(batsman_runs == 4)%>%
    group_by(id, inning, batsman)%>%
    summarise(fours_hit = n())%>%
    glimpse()%>%
    ungroup()

sixes_hit <- combined_matches_deliveries_tbl %>%
    filter(batsman_runs == 6)%>%
    group_by(id, inning, batsman)%>%
    summarise(sixes_hit = n())%>%
    glimpse()%>%
    ungroup()

batsman_aggregate <- c(batsman_score_in_a_match, balls_faced, fours_hit, sixes_hit)%>%
    select(id, inning, batsman, total_batsman_runs, deliveries_played, fours_hit, sixes_hit)

Сообщение об ошибке отображается как: -

Error: `select()` doesn't handle lists.

Требуемый вывод - это набор данных, созданный вновь созданными переменными.

1 Ответ

0 голосов
/ 16 апреля 2020

Вам нужно будет объединить эти четыре таблицы, а не объединить, используя c.

И тип соединения будет left_join, чтобы все игроки с битой были включены в вывод. Те, кто не сталкивался ни с какими шарами или не ударял границы, будут иметь NA, но вы можете легко заменить их на 0.

Я проигнорировал by, так как dplyr предполагает, что вы хотите c("id", "inning", "batsman"), только 3 общих столбца во всех четырех наборах данных.

batsman_aggregate <- left_join(batsman_score_in_a_match, balls_faced) %>%
  left_join(fours_hit) %>%
  left_join(sixes_hit) %>%
  select(id, inning, batsman, total_batsman_runs, deliveries_played, fours_hit, sixes_hit) %>%
  replace(is.na(.), 0)

# A tibble: 11,335 x 7
      id inning batsman       total_batsman_runs deliveries_played fours_hit sixes_hit
   <int>  <int> <fct>                      <int>             <dbl>     <dbl>     <dbl>
 1     1      1 DA Warner                     14                 8         2         1
 2     1      1 S Dhawan                      40                31         5         0
 3     1      1 MC Henriques                  52                37         3         2
 4     1      1 Yuvraj Singh                  62                27         7         3
 5     1      1 DJ Hooda                      16                12         0         1
 6     1      1 BCJ Cutting                   16                 6         0         2
 7     1      2 CH Gayle                      32                21         2         3
 8     1      2 Mandeep Singh                 24                16         5         0
 9     1      2 TM Head                       30                22         3         0
10     1      2 KM Jadhav                     31                16         4         1
# ... with 11,325 more rows

Есть также 2 игрока с битой, которые не сталкивались с любой доставка:

batsman_aggregate %>% filter(deliveries_played==0)
# A tibble: 2 x 7
     id inning batsman        total_batsman_runs deliveries_played fours_hit sixes_hit
  <int>  <int> <fct>                       <int>             <dbl>     <dbl>     <dbl>
1   482      2 MK Pandey                       0                 0         0         0
2  7907      1 MJ McClenaghan                  2                 0         0         0

Один из которых, по-видимому, набрал 2 пробега! Поэтому я думаю, что в столбце batsman_runs есть некоторые ошибки. Игра здесь и ясно говорит, что во второй последней поставке первых подач, 2 широких были забиты, не бежит к игроку с битой.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...