gpt4 book ai didi

r - 是否可以在 mutate 中使用过滤器?

转载 作者:行者123 更新时间:2023-12-04 11:02:22 25 4
gpt4 key购买 nike

在我下面的示例中,我正在尝试执行一个在过滤条件内进行排名的 mutate。我的最终目标是过滤,但保留完整的数据框。我只是希望我的排名根据过滤的标准来完成。我的 df_goal下面让我得到正确的等级,但需要我使用 left_join将它们添加到原始 df这似乎是一种浪费。 dplyr内有解决方案吗?这将允许我对原始 df 进行排名与 filter标准?我在想也许是 mutate 中的一个管道会起作用,但我没有成功。

例子:

library(tidyverse)

df <- tibble::tribble(
~slugSeason, ~namePlayer, ~groupPosition, ~slugPosition, ~ptsPerGame, ~astPerGame,
"2019-20", "Aaron Gordon", "F", "PF", 11.3, 3,
"2019-20", "Aaron Holiday", "G", "PG", 3, 1.8,
"2019-20", "Abdel Nader", "F", "SF", 3, 0.3,
"2019-20", "Admiral Schofield", "F", "SF", 4.4, 0.2,
"2019-20", "Al-Farouq Aminu", "F", "PF", 4.2, 1,
"2019-20", "Al Horford", "F", "PF", 18.8, 4.2,
"2019-20", "Alec Burks", "G", "SG", 8.5, 1.8,
"2019-20", "Alex Caruso", "G", "SG", 3.2, 1.6,
"2019-20", "Alex Len", "C", "C", 4.2, 1.6,
"2019-20", "Alfonzo McKinnie", "F", "SF", 0, 0
)

df <- df %>%
group_by(groupPosition) %>%
mutate(ptsRankbyPosition = rank(desc(ptsPerGame))) %>%
ungroup()

df_goal <- df %>%
group_by(groupPosition) %>%
mutate(ptsRankbyPosition = rank(desc(ptsPerGame))) %>%
ungroup() %>%
filter(slugPosition %in% c("PG", "SG", "SF") & ptsRankbyPosition > 1 |
slugPosition == "C" & ptsRankbyPosition > 1) %>%
mutate(addlRank = rank(desc(ptsPerGame)))
Created on 2019-11-05 by the reprex package (v0.3.0)

提前致谢。

最佳答案

一种选择是使用 replace创建逻辑列后

library(dplyr)
df %>%
group_by(groupPosition) %>%
mutate(ptsRankbyPosition = rank(desc(ptsPerGame))) %>%
ungroup() %>%
mutate(index = slugPosition %in% c("PG", "SG", "SF") &
ptsRankbyPosition > 1 |
slugPosition == "C" & ptsRankbyPosition > 1,
addlRank = NA_real_,
addlRank = replace(addlRank, index, rank(desc(ptsPerGame[index])))) %>%
select(-index)
# A tibble: 10 x 8
# slugSeason namePlayer groupPosition slugPosition ptsPerGame astPerGame ptsRankbyPosition addlRank
# <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
# 1 2019-20 Aaron Gordon F PF 11.3 3 2 NA
# 2 2019-20 Aaron Holiday G PG 3 1.8 3 3.5
# 3 2019-20 Abdel Nader F SF 3 0.3 5 3.5
# 4 2019-20 Admiral Schofield F SF 4.4 0.2 3 1
# 5 2019-20 Al-Farouq Aminu F PF 4.2 1 4 NA
# 6 2019-20 Al Horford F PF 18.8 4.2 1 NA
# 7 2019-20 Alec Burks G SG 8.5 1.8 1 NA
# 8 2019-20 Alex Caruso G SG 3.2 1.6 2 2
# 9 2019-20 Alex Len C C 4.2 1.6 1 NA
#10 2019-20 Alfonzo McKinnie F SF 0 0 6 5

关于r - 是否可以在 mutate 中使用过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58717057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com