我正在使用home_goal
和away_goal
创建一个新变量来查看游戏的游戏结果。
这就是我所拥有的
if(data$home_team_goal < data$away_team_goal){
data$result <- c('H')
}else if (data$home_team_goal > data$away_team_goal){
data$result<- c('A')
}else (data$home_team_goal == data$away_team_goal){
data$result<- c('D')
}
它给所有比赛带来了平局。
答案 0 :(得分:2)
您可以使用几个ifelse
语句执行此操作。我使用dplyr
包,然后您可以按名称而不是详细$
语法引用列,并使用mutate
添加新列。另外,data
不是数据框的好名字,因此我使用data1
。
install.packages("dplyr") # if required
library(dplyr)
data1 <- data.frame(home_team_goal = c(0, 0, 2, 3, 3, 1),
away_team_goal = c(1, 0, 4, 1, 4, 1))
data1 %>%
mutate(result = ifelse(home_team_goal == away_team_goal, "D",
ifelse(home_team_goal > away_team_goal, "H", "A")))
home_team_goal away_team_goal result
1 0 1 A
2 0 0 D
3 2 4 A
4 3 1 H
5 3 4 A
6 1 1 D
答案 1 :(得分:2)
以下是case_when
library(dplyr)
data %>%
mutate(result = case_when(home_team_goal == away_team_goal~"D",
home_team_goal > away_team_goal ~ "H",
TRUE ~ "A"))
# home_team_goal away_team_goal result
#1 0 1 A
#2 0 0 D
#3 2 4 A
#4 3 1 H
#5 3 4 A
#6 1 1 D
答案 2 :(得分:1)
在这种情况下,您只需要一个标签来表示两列之间的差异为>0
,0
或<0
。这只是一次比较,无需循环多个if/else
,ifelse
或case_when
:
factor(with(data1, sign(home_team_goal - away_team_goal)), labels=c("A","D","H"))
#[1] A D A H A D
#Levels: A D H
如果您不想要factor
输出:
c("A","D","H")[factor(with(data1, sign(home_team_goal - away_team_goal)))]
#[1] "A" "D" "A" "H" "A" "D"