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

R Categorising data using multiple If() statements

我创建了一个 table 足球运动员和特定位置。我现在还想将每个球员分类到他们的一般位置 (GPosition),即守门员、后卫、中场和前锋。对不起,如果这些看起来很简陋,但我对 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() 语句,但 运行 遇到了一些问题。当我 运行 我的代码时,所有 GPositions 运行 作为守门员而不是其他分类。我也不确定使用“==”是否是为此使用的正确代码。

我的部分代码:

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"
}

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

使用嵌套的 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"))