gpt4 book ai didi

rename_with 但谓词基于其他变量中的值

转载 作者:行者123 更新时间:2023-12-04 08:38:01 25 4
gpt4 key购买 nike

有没有办法 rename_with 但谓词函数不是在列名上,而是基于另一个变量中的值?
假设我有一个数据集如下:

data <- tibble(home_team = c("SF", "KC", "JAX", "WAS", "BUF"),
away_team = c("GB", "CAR", "HOU", "NYG", "SEA"),
home_total = c(21, 25, 30, 22, 23.5),
home_plays = c(65, 64, 63, 57, 60),
away_total = c(30, 22, 25, 22, 25),
away_plays = c(56, 62, 66, 59, 62))
我试图让它看起来像:
finalized_data <- tibble(team = c("SF", "KC", "JAX", "WAS", "BUF", "GB", "CAR", "HOU", "NYG", "SEA"),
total = c(21, 25, 30, 22, 23.5, 30, 22, 25, 22, 25),
plays = c(65, 64, 63, 57, 60, 56, 62, 66, 59, 62))
目前,我知道的最好方法是使用 mutate 函数,当有很多变量时它会变长,并且必须有一种更简洁的方法来做到这一点,因为它本质上是我根据数据中的变量进行的重命名。
current_way <- data %>% 
pivot_longer(c(home_team, away_team), names_to = "team_type", values_to = "team") %>%
mutate(total = ifelse(str_detect(team_type, "home_team"), home_total, away_total),
plays = ifelse(str_detect(team_type, "home_team"), home_plays, away_plays)) %>%
select(team, total, plays)
有什么想法,或者有没有办法在我缺少的枢轴函数中做到这一点?

最佳答案

这是 pivot_longer 的选项通过使用列名模式拆分为列

library(dplyr)
library(tidyr)
data %>%
pivot_longer(cols = everything(), names_to = c("grp", ".value"),
names_sep = "_") %>%
arrange(desc(grp)) %>%
select(-grp)
-输出
# A tibble: 10 x 3
# team total plays
# <chr> <dbl> <dbl>
# 1 SF 21 65
# 2 KC 25 64
# 3 JAX 30 63
# 4 WAS 22 57
# 5 BUF 23.5 60
# 6 GB 30 56
# 7 CAR 22 62
# 8 HOU 25 66
# 9 NYG 22 59
#10 SEA 25 62

关于rename_with 但谓词基于其他变量中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64706150/

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