Ignoring values or NAs in the sample function

十年热恋 提交于 2019-12-05 09:04:49

There might be a better way but sample doesn't appear to have any parameters related to NAs so instead I just wrote an anonymous function to deal with the NAs.

apply(a, 1, function(x){sample(x[!is.na(x)], size = 1)})

essentially does what you want. If you really want the matrix output you could do

b <- matrix(apply(a, 1, function(x){sample(x[!is.na(x)], size = 1)}), ncol = 1)

Edit: You didn't ask for this but my proposed solution does fail in certain cases (mainly if a row contains ONLY NAs.

a <- matrix (c(rep(5, 10), rep(10, 10), rep(NA, 5)), ncol=5, nrow=5)
# My solution works fine with your example data
apply(a, 1, function(x){sample(x[!is.na(x)], size = 1)})

# What happens if a row contains only NAs
a[1,] <- NA

# Now it doesn't work
apply(a, 1, function(x){sample(x[!is.na(x)], size = 1)})

# We can rewrite the function to deal with that case
mysample <- function(x, ...){
    if(all(is.na(x))){
        return(NA)
    }
    return(sample(x[!is.na(x)], ...))
}

# Using the new function things work.
apply(a, 1, mysample, size = 1)

I think @Dason's solution works quite well, but you can also try this:

a <- matrix (c(rep(5, 10), rep(10, 10), rep(NA, 5)), ncol=5, nrow=5)
matrix(sample(na.omit(as.numeric(a)),ncol(a)))
     [,1]
[1,]   10
[2,]    5
[3,]   10
[4,]   10
[5,]    5

Even if there is a complete row with NA's or a complete column with NA'S, this solution can deal with perfectly, for instance:

set.seed(007)
a <- matrix(sample(1:100, 25), 5)
a[1,] <- NA
a[5,1] <- NA
a[,3] <- NA
a[5,5] <- NA
a[3,2] <- NA

matrix(sample(na.omit(as.numeric(a)),ncol(a)))
     [,1]
[1,]   40
[2,]    1
[3,]   42
[4,]   26
[5,]   32

I guess this is what you were looking for (at least this could be another approach).

Tried some of the solutions above, but for some reason, I kept getting this error:

Error in sample.int(length(x), size, replace, prob): 
     invalid first argument

This code (which uses sample_n (from dplyr) and complete.cases) works like a charm, and is pretty straightforward, IMHO:

sample_n(df[complete.cases(df), ], n)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!