how to say if missing more than X?

#1
hi all,

let's say i want to take the average of 5 scores for assignments [X1 X2 X3 X4 X5].
how do i dictate missing if 2 OR MORE scores are missing? so if any 2 or more are missing then it lists average as not available? thank you
 

JesperHP

TS Contributor
#2
Code:
# 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