[R] Looping through different groups of variables in models

Jim Lemon drjimlemon at gmail.com
Thu Sep 1 00:39:07 CEST 2016


Hi Kai,
Perhaps something like this:

kmdf<-data.frame(group=rep(c("exp","cont"),each=50),
 time=factor(rep(1:5,20)),
 condition=rep(rep(c("hot","cold"),each=25),2),
 value=sample(100:200,100))
for(timeindx in levels(kmdf$time)) {
 for(condindx in levels(kmdf$condition)) {
  cat("Time",timeindx,"Condition",condindx,"\n")
  subdat<-kmdf[kmdf$time == timeindx & kmdf$condition == condindx,]
  fit<-lm(value~group,subdat)
  print(summary(fit))
  plot(subdat$group,subdat$value)
  by(subdat$value,subdat$group,mean)
 }
}

Getting elegant output is another matter. Have a look at packages
meant to produce fancier R output.

Jim


On Thu, Sep 1, 2016 at 7:58 AM, Kai Mx <govokai at gmail.com> wrote:
> Hi all,
>
> I am having trouble wrapping my head around a probably simple issue:
>
> After using the reshape package, I have a melted dataframe with the columns
> group (factor), time (int), condition (factor), value(int).
>
> These are experimental data. The data were obtained from different
> treatment groups (group) under different conditions at different time
> points.
>
> I would now like to perform ANOVA, boxplots and calculate means to compare
> groups for all combinations of conditions and time points with something
> like
>
> fit <- lm(value~group, data=[subset of data with combination of
> condition/timepoint])
> summary (fit)
> p <- ggplot([subset of data with combination of condition/timepoint],
> aes(x= group, y=value)) + geom_boxplot ()
> print (p)
> tapply ([subset of data with combination of condition/timepoint]$value,
> subset of data with combination of condition/timepoint]$group, mean)
>
> How can I loop through these combinations and output the data in an elegant
> way?
>
> Thanks so much!
>
> Best,
>
> Kai
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.



More information about the R-help mailing list