【问题标题】:replace missing with mode for factor column and mean for numeric column in r用因子列的模式和r中数字列的平均值替换缺失
【发布时间】:2018-10-09 07:40:52
【问题描述】:

我有以下名为“train”的数据框。 bflag 和 zfactor 列是因子,其他 2 列是数字。我想用模式替换因子列的缺失值,用同一数据框中的平均值替换数值变量的缺失值。我如何在 R 中做到这一点?

ID   bflag  vcount zfactor vnumber
1     0       12      1       12
2     1       NA      0       8
3     0       3       0       9
4     1       13      0       NA
5     1       2       1       2
6     NA      10      NA      NA

【问题讨论】:

    标签: r replace mean missing-data mode


    【解决方案1】:

    在基础 R 中,您可以遍历列并使用简单的 if 语句。我们必须为模式定义一个函数,因为基础 R 没有提供一个函数。

    df[-1] <- lapply(df[-1], function(x) {
        if(is.factor(x)) replace(x, is.na(x), Mode(na.omit(x)))
        else if(is.numeric(x)) replace(x, is.na(x), mean(x, na.rm=TRUE))
        else x
    })
    
    df
    #   ID bflag vcount zfactor vnumber
    # 1  1     0     12       1   12.00
    # 2  2     1      8       0    8.00
    # 3  3     0      3       0    9.00
    # 4  4     1     13       0    7.75
    # 5  5     1      2       1    2.00
    # 6  6     1     10       0    7.75
    

    数据和Mode函数:

    df <- read.table(text = "ID   bflag  vcount zfactor vnumber
    1     0       12      1       12
    2     1       NA      0       8
    3     0       3       0       9
    4     1       13      0       NA
    5     1       2       1       2
    6     NA      10      NA      NA", 
    colClasses = rep(c("numeric", "factor"), length.out=5), 
    header = TRUE)
    
    Mode <- function(x) {
        ux <- unique(x)
        ux[which.max(tabulate(match(x, ux)))]
    }
    

    Mode借自Is there a built-in function for finding the mode?

    【讨论】:

    • 非常感谢您的回答。在实施mean 后,我一直在努力寻找一种计算模式的方法,但您的回答解决了我的问题。我已经在我的回答中提到了你,希望你不要介意。
    • @MKR - 完全没问题 :)
    【解决方案2】:

    dplyr::mutate_if 将有助于确定该列所需的列类型和函数/操作(mode/mean)。解决方案是:

    library(dplyr)
    df %>% mutate_if(is.numeric, funs(replace(.,is.na(.), mean(., na.rm = TRUE)))) %>%
      mutate_if(is.factor, funs(replace(.,is.na(.), Mode(na.omit(.)))))
    
    #   ID bflag vcount zfactor vnumber
    # 1  1     0     12       1   12.00
    # 2  2     1      8       0    8.00
    # 3  3     0      3       0    9.00
    # 4  4     1     13       0    7.75
    # 5  5     1      2       1    2.00
    # 6  6     1     10       0    7.75
    

    注意:Mode 函数取自 @RichScriven 答案。 Mode 函数的链接位于 (Is there a built-in function for finding the mode?)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      • 2020-09-04
      • 2019-09-17
      • 2018-02-05
      相关资源
      最近更新 更多