Hi, dat1<- read.table(text=" x1 x2 x3 a1 b2 2 a1 b4 4 a2 NA 3 NA b2 6 a3 b1 NA a1 b2 9 a1 b2 NA a1 b4 2 ",sep="",header=TRUE,stringsAsFactors=FALSE) dat2<- dat1 dat2$x4<-with(dat2,ave(x3,x1,x2,FUN=function(x) mean(x,na.rm=TRUE))) dat2 # x1 x2 x3 x4 #1 a1 b2 2 5.5 #2 a1 b4 4 3.0 #3 a2 <NA> 3 3.0 #4 <NA> b2 6 6.0 #5 a3 b1 NA NaN #6 a1 b2 9 5.5 #7 a1 b2 NA 5.5 #8 a1 b4 2 3.0
A.K. >My data contains the following x1 x2 x3 vectors and I want to create a new vector x4 by performing calculations on x3 based on criteria from x1 and >x2. The data contains missing values. > >x1 x2 x3 x4 >a1 b2 2 mean(x3) when x1=a1 and x2=b2 >a1 b4 4 mean(x3) when x1=a1 and x2=b4 >a2 NA 3 NA >NA b2 6 NA >a3 b1 NA mean(x3) when x1=a3 and x2=b1 >a1 b2 9 mean(x3) when x1=a1 and x2=b2 >: : : > > >That is I am willing to create a group mean vector and the group means will >correspond to the members of that group. >stata handles this with a "by" option. Can I create such vectors based on >conditional calculations in R ? ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.