【发布时间】:2019-10-09 13:47:14
【问题描述】:
我是 R 的新手,并且在很长一段时间后才开始使用它。 我从该站点获得了 NFL 第 1 周的数据,并尝试执行一个小的 ifelse,但它不起作用。 我想要结果字段中的团队名称
#this works only when condition is true and doesn't when condition is false
wk1$tm_won= if_else(wk1$home_score < wk1$away_score, wk1$away_team, wk1$home_team)
#this doesn't work - gives me the difference
wk1$tm_won1 <- ifelse(wk1$home_score < wk1$away_score, wk1$away_team, wk1$home_team)
#this doesn't work - gives me difference and not the team name
wk1 %>%
mutate(tm_won2 = ifelse (home_score < away_score, away_team,
ifelse (home_score > away_score, home_team, NA)))
#this doesn't work
wk1 %>%
mutate(tm_won = case_when(
home_score < away_score ~ away_team,
home_score > away_score ~ home_team,
TRUE ~ a ))# DRAW
我的结果数据集:
season week home_team away_team home_score away_score tm_won tm_won1 tm_won2
2019 1 CHI GB 3 10 GB 7 7
2019 1 CAR LA 27 30 LA 11 11
2019 1 PHI WAS 32 27 <NA> 14 14
2019 1 NYJ BUF 16 17 BUF 3 3
2019 1 MIN ATL 28 12 <NA> 9 9
【问题讨论】:
-
你能详细说明这里的“不起作用”是什么意思吗?
-
数据中看起来像字符串的内容可能是因素。将数据读取为字符串,或将因子转换为字符串。然后你的代码就可以工作了。
标签: r if-statement