[R] save results in a loop
Greg Snow
538280 at gmail.com
Wed Aug 13 23:27:41 CEST 2014
Generally if you want to save the results of a loop then it is time to
learn to use the lapply and sapply functions instead.
Try something like:
Tukey <- lapply( 6:n, function(i) Tukey1 = HSD.test(lm(sdata_mg[,i] ~
sdata_mg$Medium+sdata_mg$color+sdata_mg$type+sdata_mg$Micro),
'sdata_mg$Micro') )
though that is still ugly with all those subscripting `$`s. A little
nicer might be:
tmpfun <- function(vname) {
tmp.f <- as.formula( paste( vname, '~ Medium + color + type + Micro') )
HSD.test( lm(tmp.f, data=sdata_mg), 'Micro' )
}
Tukey <- lapply( names(sdata_mg)[6:n], tmpfun )
or
tmpfun <- function(vname) {
vname <- as.name(vname)
HSD.test(
eval(substitute(
lm(vname ~ Medium + color + type + Micro, data=sdata_mg)
)), 'Micro')
}
Tukey <- lapply(names(sdata_mg)[6:n], tmpfun)
On Wed, Aug 13, 2014 at 1:43 PM, Wenlan Tian <tianwenlan at gmail.com> wrote:
> Hi, i'm new to R. I have a question about how to save results in a loop to
> a file. Here is an example:
>
> for (i in 6:n){
> Tukey1 = HSD.test(lm(sdata_mg[,n] ~
> sdata_mg$Medium+sdata_mg$color+sdata_mg$type+sdata_mg$Micro),
> 'sdata_mg$Micro')
> }
>
>
> I don't know how to do it with the loop for all data, so i just tried one
> of them,
> Tukey1 = HSD.test(lm(sdata_mg[,1] ~
> sdata_mg$Medium+sdata_mg$color+sdata_mg$type+sdata_mg$Micro),
> 'sdata_mg$Micro')
> Tukey1
>
> The results look like this:
>
> $statistics
> Mean CV MSerror HSD r.harmonic
> 11.87421 3.102479 0.1357148 0.5288771 7.384615
>
> $parameters
> Df ntr StudentizedRange
> 24 4 3.901262
>
> $means
> sdata_mg[, 6] std r Min Max
> 111d 11.86369 0.5317421 6 11.08623 12.45651
> 125d 11.74433 0.1663130 6 11.53504 12.02412
> 14d 11.54073 0.3877921 8 10.80300 11.96797
> Ground 12.16673 0.3391952 12 11.56278 12.86199
>
> $comparison
> NULL
>
> $groups
> trt means M
> 1 Ground 12.16673 a
> 2 111d 11.86369 ab
> 3 125d 11.74433 ab
> 4 14d 11.54073 b
>
>
> How could i get all the results in the loop?
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
--
Gregory (Greg) L. Snow Ph.D.
538280 at gmail.com
More information about the R-help
mailing list