【问题标题】:Suggestion to replace NA with the mode [duplicate]建议用模式替换 NA [重复]
【发布时间】:2022-01-20 19:02:57
【问题描述】:

在之前的实验中,我偶尔会用平均值代替 NA。到目前为止,这段代码已经奏效了。

df <- transform(df,
                 var_1 = ave(var_1, group,
                             FUN = function(x) replace(x, is.na(x),
                                                       mean(x, na.rm = T))))
df

我的数据也被分类了。

df <- data.frame(group = c(rep("cake", 5), rep("cookie",5)),
                    var_1 = c(1, 2, NA, 3, 1, 8, 9, NA, 7, 8))
df

我正在寻找的结果。

    group var_1
1    cake     1
2    cake     2
3    cake     1
4    cake     3
5    cake     1
6  cookie     8
7  cookie     9
8  cookie     8
9  cookie     7
10 cookie     8

我尝试使用 dplyr 包将 NA 替换为模式。但是,它没有用。相反,我收到了一条错误消息。

# not working
library(dplyr)
df %>% group_by(group) %>% mutate(var_1 = na.aggregate(var_1, FUN = mode))

此外,此代码也不起作用。

# not working
library(dplyr)
df %>% group_by(group) %>% mutate(var_1 = if_else(is.na(var_1), 
                         calc_mode(var_1), var_1))

这是一个错误示例。

Error: Problem with `mutate()` column `var_1`.
ℹ `var_1 = if_else(is.na(var_1), calc_mode(var_1), var_1)`.
x could not find function "calc_mode"
ℹ The error occurred in group 1: group = "cake".
Error: Problem with `mutate()` column `var_1`.
ℹ `var_1 = na.aggregate(var_1, FUN = mode)`.
x could not find function "na.aggregate"
ℹ The error occurred in group 1: group = "cake".

任何想法将不胜感激。非常感谢您的建议。

【问题讨论】:

  • 这两个错误都表明您正在使用未加载的函数。当您加载您尝试使用的软件包时,您是否仍然收到错误消息?
  • 是的。我确定我正确加载了包。非常感谢您的建议。

标签: r dplyr


【解决方案1】:
na_replace_Mode <- function(x) {
  ux <- unique(na.omit(x))
  x[is.na(x)] <- ux[which.max(tabulate(match(x, ux)))]
  x
}

transform(df, var_1 = ave(var_1, group, FUN = na_replace_Mode))

   group var_1
1    cake     1
2    cake     2
3    cake     1
4    cake     3
5    cake     1
6  cookie     8
7  cookie     9
8  cookie     8
9  cookie     7
10 cookie     8

你也可以这样做:

Mode <- function(x) {
  x <- na.omit(x)
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

df %>%
   group_by(group) %>%
   mutate(var_1 = replace_na(Mode(var_1)))
# A tibble: 10 x 2
# Groups:   group [2]
   group  var_1
   <chr>  <dbl>
 1 cake       1
 2 cake       2
 3 cake       1
 4 cake       3
 5 cake       1
 6 cookie     8
 7 cookie     9
 8 cookie     8
 9 cookie     7
10 cookie     8

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2016-08-29
    相关资源
    最近更新 更多