[R] (sans objet)

Jim Lemon jim at bitwrit.com.au
Fri Oct 4 01:14:24 CEST 2013


On 10/04/2013 08:42 AM, Jesse Gervais wrote:
> Hello there,
>
> I try to construct a variable with R, but I have some difficulties.
>
> Assume that I use a data set named = mydata. I want to create a variable
> that is the mean (totmean) or the sum (totsum) of 6 variables (var1, var2,
> var3, var4, var5, var6). However, I want only participants who have
> responded to at least 4 items to be include. Those who have one or two
> missing for var1-var6 should be coded NA for totmean and totsum.
>
> How I do that?
>
Hi Jesse,
Say your data looks like this:

mydata<-data.frame(var1=rnorm(100),var2=rnorm(100),
  var3=rnorm(100),var4=rnorm(100),
  var5=rnorm(100),var6=rnorm(100))
mydata$var1[sample(1:100,20)]<-NA
mydata$var2[sample(1:100,20)]<-NA
mydata$var3[sample(1:100,20)]<-NA
mydata$var4[sample(1:100,20)]<-NA
mydata$var5[sample(1:100,20)]<-NA
mydata$var6[sample(1:100,20)]<-NA
valid.n<-function(x) return(sum(!is.na(x)))
gt4<-unlist(apply(as.matrix(mydata),1,FUN=valid.n))<=4
totmean<-mean(unlist(mydata[gt4,]),na.rm=TRUE)
totsum<-sum(unlist(mydata[gt4,]),na.rm=TRUE)

Jim



More information about the R-help mailing list