[R] A better way to do this
1Rnwb
sbpurohit at gmail.com
Thu May 19 20:29:50 CEST 2011
Hello gurus,
I have a dataframe containing two groups viz., 'control' and 'case', each of
these groups contains longitudinal data for 100 subjects. I have to plot all
these subjects on a single chart and then put a regression line for each of
the group for all the subjects. I have written a function to do the chart
grpcharts<-function (dat, group,group2,molecule,cutoff){
dat2<-dat[grep(group,dat$Group),]
ylim=log2(c(min(dat2[,molecule],na.rm=T)+4,max(dat2[,molecule],na.rm=T)+1))
all.sub.id<-dat2$Subject.ID
if (group=='control'){
col=c('blue')
}else{col=c('red')}
if(group2=='case'){
col2=c('red')
}else{ col2=c('blue')}
uniq.sub.id<-unique(all.sub.id)
errcol<-c()
for (i in 1: length(uniq.sub.id))
{
sub<-dat2[grep(uniq.sub.id[i],dat2$Subject.ID),]
sub<- sub[order(sub$Age.at.Sample.Collection),]
sub<-sub[sub[,molecule]>cutoff,]
sub.id<-uniq.sub.id[i]
if (dim(sub)[1]<=1) errcol<-c(errcol, sub.id)
if (dim(sub)[1]>1)
{
par(new=TRUE)
plot(log2(sub[,molecule])~sub$Age.at.Sample.Collection,
ylab=paste('Log2_',molecule,sep=''),xlab="Age at Sample",pch=1, ylim=ylim,
xlim=c(0,25),main=paste(group,'-',molecule))
mod<-loess(log2(sub[,molecule])~Age.at.Sample.Collection,
na.action=na.exclude, data=sub)
pred<-predict(mod)
lines(pred~Age.at.Sample.Collection, data=sub,lwd=1, lty=1)
}
}
dat2<-dat2[order(dat2$Age.at.Sample.Collection),]
mod<-loess(log2(dat2[,molecule])~Age.at.Sample.Collection,
na.action=na.exclude, data=dat2)
pred<-predict(mod)
lines(pred~Age.at.Sample.Collection, data=dat2,lwd=2, lty=1,col=col)
dat2<-dat[grep(group2,dat$Group),]
dat2<-dat2[order(dat2$Age.at.Sample.Collection),]
mod<-loess(log2(dat2[,molecule])~Age.at.Sample.Collection,
na.action=na.exclude, data=dat2)
pred<-predict(mod)
lines(pred~Age.at.Sample.Collection, data=dat2,lwd=2, lty=1,col=col2)
legend(c(20,20),c(ylim),c(group,group2), lty=1,lwd=2,col=c(col,col2),
bty='n')
print('done')
}
the function subsets the data based on the 'group' and plots the datapoints
currently I am using a loop to assign the colors under two conditions. I
need some pointers to assign the colors to the regression lines for the two
groups without using a loop.
thanks
sharad
--
View this message in context: http://r.789695.n4.nabble.com/A-better-way-to-do-this-tp3536576p3536576.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list