用行模式替换 NA 的 R 循环

R loop for NA replacement with mode of row

head(df)
    Name    Score1    Score2    Score3    Score4    Score5
1   John     2           2        NA        3         NA
2   Sam      1           NA        3        1          1

我正在尝试编写一个循环来遍历每一行,并将每个用户的 NA 替换为他们的分数模式;例如,John 的 NA 将替换为“2”,而 Sam 的 NA 将替换为“1”;

我目前有这个用于模式计算,但无法弄清楚如何用该行的模式替换同一循环中的 NA。

Mode <- function(x, na.rm = TRUE) {
  if(na.rm){
    x = x[!is.na(x)]
  }

  ux <- unique(x)
  return(ux[which.max(tabulate(match(x, ux)))])
 }



df$Row_Mode <- 0
for (row in 1:nrow(df){
  df[row,]$Row_Mode <- as.numeric(Mode(df[row,2:6]))
}

在这个循环中,如何同时用该用户的模式替换 NA?

您可以简单地 apply 函数遍历数据框的行,然后转置结果,而不是循环。请注意,必须省略 Name 列,正如 David Arenburg 指出的那样。

正如 Frank 在评论中提到的,您可以使用 df[, -1].

直接替换 Name 列以外的行
df[, -1] <- t(apply(df[-1], 1, function(x){x[is.na(x)] <- Mode(x); x}))
df
#   Name Score1 Score2 Score3 Score4 Score5
# 1 John      2      2      2      3      2
# 2  Sam      1      1      3      1      1

这假设 Mode 定义为您的问题。