【问题标题】:Generate random number of missing values in R在 R 中生成随机数的缺失值
【发布时间】:2014-01-06 14:21:04
【问题描述】:

我有一个这样的数据框:

df<-data.frame(time1=rbinom(100,1,0.3),
               time2=rbinom(100,1,0.4),
               time3=rbinom(100,1,0.5),
               time4=rbinom(100,1,0.6))

如何为每个时间变量生成随机缺失值,其中缺失的数量高达 20%?即,在这种情况下,每列的缺失总数小于20,并且它们是从主题(行)中随机缺失的。

【问题讨论】:

    标签: r random


    【解决方案1】:

    你可以这样做:

    insert_nas <- function(x) {
      len <- length(x)
      n <- sample(1:floor(0.2*len), 1)
      i <- sample(1:len, n)
      x[i] <- NA 
      x
    }
    
    df2 <- sapply(df, insert_nas)
    df2
    

    这将使您每列最多有 20% 的缺失

    colSums(is.na(df2)) / nrow(df2)
    
    time1 time2 time3 time4 
     0.09  0.16  0.19  0.14 
    

    【讨论】:

    • 我更喜欢n &lt;- sample.int(floor(0.2*len), 1); i &lt;- sample(seq_along(x), n)
    【解决方案2】:

    这是一种方法:

    as.data.frame(lapply(df, function(x) 
                   "is.na<-"(x, sample(seq(x), floor(length(x) * runif(1, 0, .2))))))
    

    【讨论】:

      【解决方案3】:

      你的意思是这样的?

      nomissing <- sample(1:20,1)
      testnos <- rbinom(100 - nomissing,1,0.3)
      testnas <- rep(NA,nomissing)
      testmix <- sample(x = c(testnos,testnas),100)
      

      输出 -

      > testmix
        [1]  1  0  0  0  0  0  1  0  0  0  1  1  0  0  0  0  0  1  1  0  0  0  0  0  0  1  0  0  0  0  0  0  0  1  0  0
       [37]  1  0  0  0  1  1  0  1  0  0  1  0  0  0  0  1  0  1  0  0  0  0  0  1  0  1  0  0  1  1  1 NA  0  1  0  0
       [73]  0  0  1  1  0  0  1  0  0  1  1  0  0 NA  1  0  0  0  0  0  1  0 NA NA  1  0  0  0
      

      【讨论】:

      • 缺失值最多20个,表示每个变量可能有1-20个范围内的任意缺失值。而且行数还是100。
      猜你喜欢
      • 1970-01-01
      • 2013-06-01
      • 2018-12-11
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      相关资源
      最近更新 更多