R使用多个If()语句对数据进行分类

时间:2017-12-03 22:54:03

标签: r if-statement categories which

我创建了一个包含足球运动员和特定位置的桌子。我现在也想将每个球员分类为他们的一般位置(GP),即守门员,后卫,中场和前锋。对不起,如果这些看起来很简陋,但我对R来说很新。

我的部分数据如下:

            Player      Position  GPosition
1  Thibaut Courtois       Keeper  Goalkeeper
2   Willy Caballero       Keeper  Goalkeeper
9           Eduardo       Keeper  Goalkeeper
17      Matej Delac       Keeper  Goalkeeper
19       David Luiz  Centre-Back  Goalkeeper
22  Antonio Rüdiger  Centre-Back  Goalkeeper

我尝试过使用If()或Which()语句,但遇到了一些问题。当我运行我的代码时,所有GPosition都作为GoalKeeper而不是其他分类运行。我也不确定是否使用了" =="是用于此目的的正确代码。

我的部分代码:

PlayerPositions$GPosition <- if(PlayerPositions$Position == "Keeper") {
  PlayerPositions$GPosition <- "Goalkeeper"
} else if (PlayerPositions$Position == "Centre-Back"){
  PlayerPositions$GPosition <- "Defender"
} else if (PlayerPositions$Position == "Left-Back"){
  PlayerPositions$GPosition <- "Defender"
} else if (PlayerPositions$Position == "Right-Back"){
  PlayerPositions$GPosition <- "Defender"

等......直到最后一行:

} else if (PlayerPositions$Position == "Right Wing") {
  PlayerPositions$GPosition <- "Forward"
}

2 个答案:

答案 0 :(得分:0)

我会考虑使用case_when中的dplyr而不是多个ifelse语句

答案 1 :(得分:0)

使用嵌套ifelse代替ifelse。以下是原因和方法:

x <- c(1,2,3)
if (x==2) print("hello") else print("world")
# [1] "world"
# Warning message:
#   In if (x == 2) print("hello") else print("world") :
#   the condition has length > 1 and only the first element will be used

此处的条件是x==2的结果,即FALSE, TRUE, FALSE。如果您只使用x

中的一个元素,警告就会消失
if (x[1]==2) print("hello") else print("world")
# [1] "world"

现在,使用ifelse代替,您会得到三个值 - x的每个元素都有一个值:

ifelse(x==2, "hello", "world")
# [1] "world" "hello" "world"

ifelse(x==2, "hello", ifelse(x==1, "HELLO", "world"))
# [1] "HELLO" "hello" "world"

所以在你的情况下:

PlayerPositions$GPosition <- 
  ifelse(PlayerPositions$Position == "Keeper", "Goalkeeper", 
    ifelse(PlayerPositions$Position %in% paste(c("Center", "Left", "Right"), "Back", sep="-"), "Defender", "Forward"))