[R] for loop, error in model frame.default ... variable lengths differ

Joshua Wiley jwiley.psych at gmail.com
Mon May 21 11:23:29 CEST 2012


On Mon, May 21, 2012 at 2:00 AM, peter dalgaard <pdalgd at gmail.com> wrote:
[snip]
> What the poster probably wanted was something in the vein of
>
>> nm <- colnames(airquality)[1]
>> ff <- formula(bquote(.(as.name(nm))~Month))
>> aggregate(ff, airquality, mean, na.rm=T)
>  Month    Ozone
> 1     5 23.61538
> 2     6 29.44444
> 3     7 59.11538
> 4     8 59.96154
> 5     9 31.44828

or perhaps to use an implicit loop (since looping seemed to be part of it all):

results <- lapply(c("Ozone", "Solar.R"), function(n) {
  aggregate(. ~ Month, airquality[, c(n, "Month")], mean, na.rm = TRUE)
  })

## print results
results


## untested code based on OPs original example
vars <- colnames(df)[c(10,12,16,18,20,21,24:29,45)]
results <- lapply(vars, function(n) {
  aggregate(. ~ x1 + x2 + x3, df[, c(n, "x1", "x2", "x3")], mean, na.rm = TRUE)
  })

## print results
results

Cheers,

Josh

> --
> Peter Dalgaard, Professor
> Center for Statistics, Copenhagen Business School
> Solbjerg Plads 3, 2000 Frederiksberg, Denmark
> Phone: (+45)38153501
> Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com
>
> ______________________________________________
> 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.

-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list