在R中生成随机数的缺失值

Dav*_*d Z 3 random r

我有一个像这样的数据框:

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))
Run Code Online (Sandbox Code Playgroud)

如何为每个时间变量生成随机缺失值,最多丢失20%?即,在这种情况下,每列中丢失的总数少于20,并且从主题(行)中随机丢失它们.

Mar*_*ann 7

你可以这样做:

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
Run Code Online (Sandbox Code Playgroud)

这将为您提供每列最多20%的缺失

colSums(is.na(df2)) / nrow(df2)

time1 time2 time3 time4 
 0.09  0.16  0.19  0.14 
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢`n < - sample.int(floor(0.2*len),1); 我< - 样本(seq_along(x),n)`. (2认同)

Sve*_*ein 5

这是一种方法:

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