[R] parameterization question
William Dunlap
wdunlap at tibco.com
Sat Sep 6 01:28:16 CEST 2014
You could try using the non-formula interface to aggregate.
Note that the following two calls to aggregate are equivalent but
the second (using the non-formula interface) makes the response column
a variable:
> df <- data.frame(Y1=1:10, Y2=101:110, Group=rep(letters[1:3], c(3,3,4)))
> aggregate(Y1 ~ Group, data=df, FUN=sum)
Group Y1
1 a 6
2 b 15
3 c 34
> responseColumn <- "Y1"
> aggregate(df[responseColumn], by=df["Group"], FUN=sum)
Group Y1
1 a 6
2 b 15
3 c 34
Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Fri, Sep 5, 2014 at 10:57 AM, Dale Garman <garman.dale at gmail.com> wrote:
> How can I parameterize the function call to aggregate() below with colx (a
> character string) in the following code? That is, replace both if
> statements with aaa <- aggregate(colx_something, data=tidy[grpyrs,],sum).
> I've tried a couple of ideas for "colx_something" but get an R-error each
> time. Been using R for 5-6 months and want to expand my knowledge.
>
> explain_causes <- function(spread, colx, peakyears) {
> for(i in peakyears) {
> grpyrs <- tidy$year >= (i-spread) & tidy$year <= (i+spread)
> if(colx == "harm")
> aaa <- aggregate(harm ~ EVTYPE, data=tidy[grpyrs,],sum)
> if(colx == "damage")
> aaa <- aggregate(damage ~ EVTYPE, data=tidy[grpyrs,],sum)
> .
> .
> .
> }
> }
>
> # "harm" is a column var in tidy dataframe
> explain_causes(0,"harm",c(1953,1965,1974,1979,1984,1995,1998,2011))
>
> # "damage" is a column var in tidy dataframe
> explain_causes(0,"damage",c(2005,2006))
>
> [[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.
More information about the R-help
mailing list