Randomly insert NAs into dataframe proportionaly

后端 未结 6 1448
無奈伤痛
無奈伤痛 2020-11-29 12:07

I have a complete dataframe. I want to 20% of the values in the dataframe to be replaced by NAs to simulate random missing data.

A <- c(1:10)
B <- c(1         


        
6条回答
  •  爱一瞬间的悲伤
    2020-11-29 12:45

    May i suggest a first function (ggNAadd) designed to do this, and improve it with a second function providing graphical distribution of the NAs created (ggNA)

    What is neat is the possibility to input either a proportion of a fixed number of NAs.

    ggNAadd = function(data, amount, plot=F){
      temp <- data
      amount2 <- ifelse(amount<1, round(prod(dim(data))*amount), amount)
      if (amount2 >= prod(dim(data))) stop("exceeded data size")
      for (i in 1:amount2) temp[sample.int(nrow(temp), 1), sample.int(ncol(temp), 1)] <- NA
      if (plot) print(ggNA(temp))
      return(temp)
    }
    

    And the plotting function:

    ggNA = function(data, alpha=0.5){
      require(ggplot2)
      DF <- data
      if (!is.matrix(data)) DF <- as.matrix(DF)
      to.plot <- cbind.data.frame('y'=rep(1:nrow(DF), each=ncol(DF)), 
                                  'x'=as.logical(t(is.na(DF)))*rep(1:ncol(DF), nrow(DF)))
      size <- 20 / log( prod(dim(DF)) )  # size of point depend on size of table
      g <- ggplot(data=to.plot) + aes(x,y) +
        geom_point(size=size, color="red", alpha=alpha) +
        scale_y_reverse() + xlim(1,ncol(DF)) +
        ggtitle("location of NAs in the data frame") +
        xlab("columns") + ylab("lines")
      pc <- round(sum(is.na(DF))/prod(dim(DF))*100, 2) # % NA
      print(paste("percentage of NA data: ", pc))
      return(g)
    }
    

    Which gives (using ggplot2 as graphical output):

    ggNAadd(df, amount=0.20, plot=TRUE)
    ## [1] "percentage of NA data:  20"
    ##     A  B  c
    ## 1   1 11 21
    ## 2   2 12 22
    ## 3   3 13 23
    ## 4   4 NA 24
    ## ..
    

    enter image description here

    Of course, as mentioned earlier, if you ask too many NAs the actual percentage will drop because of repetitions.

提交回复
热议问题