```
# artificial data
m=5
n=100
N=n*m
mydata=rnorm(N)
NAindex=sample(c(1,0),N,prob=c(0.1,0.9),replace=TRUE)
mydata[as.logical(NAindex)]=NA
M=matrix(mydata,nrow=n,ncol=m)
# function that does what you ask
mymean=function(x,numberNA=2)
{
if (sum(is.na(x))>=2) {return(NA)} else {return(mean(x,na.rm=TRUE))}
}
# apply mymean
out=apply(M,MARGIN=1,FUN=mymean)
# test
which(is.na(out))
which(rowSums(is.na(M))>=2)
# alternative procedure
out2=rowMeans(M,na.rm=TRUE) # do mean of all rows
out2[which(rowSums(is.na(M))>=2)]=NA # overwrite those in out where M has two or more NA
```