试图通过比较其他2个来变量

时间:2017-09-29 03:16:24

标签: r if-statement

我正在使用home_goalaway_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')
}
它给所有比赛带来了平局。

3 个答案:

答案 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)

在这种情况下,您只需要一个标签来表示两列之间的差异为>00<0。这只是一次比较,无需循环多个if/elseifelsecase_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"