我正在尝试使用DPLYR检索和汇总数据。我写了下面的代码,它可以工作,但是我想将所有这些结合成一个语句。这可能吗?
创建数据集
set.seed(1)
dbo_games <- data.frame(
name = sample(c("Team1","Team2","Team3","Team4","Team5","Team6","Team7","Team8","Team9","Team10")),
total_games = sample(1:10)
)
set.seed(1)
dbo_wins <- data.frame(
name = sample(c("Team1","Team2","Team3","Team4","Team5","Team6","Team7","Team8","Team9","Team10")),
tota_wins = sample(c("yes", "no"), 10, replace = TRUE)
)
total_games <- con %>% tbl("dbo_games")
total_wins <- con %>% tbl("dbo_wins")
total<- total_games %>% filter(games > 12) %>%
group_by(NAME) %>%
summarise(total_games = n_distinct(game_id)) %>% collect()
wins <- total_wins %>% filter( win == 'Y') %>%
group_by(NAME) %>%
summarise(total_wins = n_distinct(game_id)) %>% collect()
perc_win <- total %>% left_join(wins) %>%
mutate(pct_won = total_wins/total_games)
此代码有效,但我相信可能会有更简洁的代码编写方式来达到相同的结果。有什么想法吗?
答案 0 :(得分:1)
如果您共享示例数据以及执行工作的原因,那么解决这个问题会更容易。
但是,您仍然可以按如下所示将它们链接在一起:
total_games %>%
filter(games > 12) %>%
group_by(NAME) %>%
summarise(total_games = n_distinct(game_id)) %>%
left_join(total_wins %>% filter( win == 'Y') %>%
group_by(NAME) %>%
summarise(total_wins = n_distinct(game_id))) %>%
mutate(pct_won = total_wins/total_games)