我试图根据他们是否包含在“home_lineup”或“away_lineup”字符串中为我的数据框中的每个球员分配团队价值。
我已经使用了该str_detect
功能,除此之外,我还没有找到解决问题的替代方法。
此链接中包含数据框的快照,其中包含 season_data_select 分配。
library(gsheet)
url <- 'https://docs.google.com/spreadsheets/d/1Z1njK5FxCZgIUaxxoRUVaK8DFNWP4OGthT6kuFHcC7I/edit?usp=sharing'
season_data_select <- gsheet2tbl(url)
https://docs.google.com/spreadsheets/d/1Z1njK5FxCZgIUaxxoRUVaK8DFNWP4OGthT6kuFHcC7I/edit?usp=sharing
library(dplyr)
season_data_select <- season_data_select %>%
mutate(player_team = ifelse(str_detect(player, home_lineup),
home,
away))
理想情况下,我正在寻找一个代码,它将引入一个新列 (player_team),它将采用“player”列中的值并检查它是否在“home_lineup”列中。如果是,则返回“home”列中的值。如果不是,则返回“离开”列值。或者,我可以看到它是“如果在'home_lineup'中,返回'home',如果在'away_lineup'中,返回'away'”
使用时,当前代码返回值 away,这让我相信在尝试使用 'player' 值引用 'home_lineup' 列时存在问题。所有涉及的变量都在字符类中。
由于str_detect
在字符串和模式上进行了矢量化,我们可以使用它。同样为了获得带有"home"
和"away"
关键字的新列,我们可以使用相同的str_detect
library(dplyr)
library(stringr)
season_data_select %>%
mutate(player_team = if_else(str_detect(home_lineup, player), home, away),
new = c("away", "home")[str_detect(home_lineup, player) + 1])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句