【问题标题】:R Impute DataTable Mode And MiceR Impute DataTable 模式和小鼠
【发布时间】:2020-03-18 15:07:53
【问题描述】:
# IMPUTING VALUES
library(data.table)
set.seed(1337)
mydt = q <- data.table(Year = rep(2000:2005, each = 10),
                   Type = c("A","B"),
Class = sample(1:5,rep=T),
                   Car = sample(0:1, rep=T),
                   Boat = sample(1:4, rep=T)
)
naRows <- sample(nrow(mydt),15)
mydt[ naRows, Car := NA]
naRows <- sample(nrow(mydt),15)
mydt[ naRows, Boat := NA]
setkey(mydt,Year,Type)

我所有的数据都是类别和二进制。

我想做两件事。

首先我希望按类型和类别来估算 Car 和 Boat 的模式。因此,对于 Type 和 Class 的每种组合,找到 Car 和 Boat 的模式并估算它们。

其次我想知道:: 是否也可以使用“老鼠”来做到这一点?

我正在寻找 data.table 和鼠标解决方案。我希望两者都有,因为“老鼠”在我的大数据中可能需要很长时间!

【问题讨论】:

    标签: r data.table imputation r-mice


    【解决方案1】:

    如果我正确理解了您的请求(您想用 Type x Class 列的模式替换缺失),这可能是data.table 解决方案:

    # function to calculate mode
    stats_mode <- function(x) {
      ux <- unique(x[!is.na(x)])
      ux[which.max(tabulate(match(x, ux)))]
    }
    
    # Generate new column with mode per group
    mydt[, `:=`(mCar  = stats_mode(Car),
                mBoat = stats_mode(Boat)), by = .(Type, Class)]
    
    # Replace missings
    mydt[is.na(Car),  Car  := mCar]
    mydt[is.na(Boat), Boat := mBoat]
    
    # Cleansing
    mydt[, c("mBoat", "mCar") := NULL]
    

    对于大数据,您可能希望避免包含模式的两列的具体化。相反,您可以存储一个汇总表并将其用作一种查找表来查找每个组的模式值。

    【讨论】:

      猜你喜欢
      • 2015-03-27
      • 2020-11-02
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 2020-08-11
      • 2013-09-23
      相关资源
      最近更新 更多