0

I am quite new to R and struggling with the following issue:

        Country.Name variable Quantity
    1         World     1977  2524966
    2         World     1978  2552326
    3         World     1979  2710504
    4         World     1980  2732926
    5         World     1981  2636113
    6         World     1982  2803907
    7         World     1983  2778356
    8         World     1984  2693296
    9         World     1985  2695397
    10        World     1986  2747397
    (...)
    30        World     2006  3100186

For df$Quantity (numeric) I want to calculate two separate means, from (1) 1977 to 1991 and from (2) 1992 to 2006. Further search hasn't helped me solve that issue, so I'd be glad to hear if anyone could help me out with this!

Best, Jannis

Jannis H.
  • 3
  • 2
  • 1
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Sotos Nov 07 '18 at 10:08
  • Here is an `aggregate` to get you started, `aggregate(Quantity ~ with(df, ifelse(variable >= 1977 & variable <= 1991, 1, 2)), df, mean)` – Sotos Nov 07 '18 at 10:15
  • @Sotos We must be eating the same cereal or something. – Tim Biegeleisen Nov 07 '18 at 10:17
  • @TimBiegeleisen kelloggs frosties :) – Sotos Nov 07 '18 at 10:19
  • Thanks Sotos! I'll do my best ;) – Jannis H. Nov 07 '18 at 10:21
  • `aggregate(Quantity ~ (variable <= 1991), data=df, FUN=mean)` – jogo Nov 07 '18 at 10:22

1 Answers1

1

Here is a base R option:

aggregate(df$Quantity,
    by=list(ifelse(df$variable >= 1977 & df$variable <= 1991, 0, 1)),
    FUN=mean)

This buckets rows from 1977 to 1991 (inclusive on both ends) into a zero bucket, and all others years into a 1 bucket. Then, aggregate finds the mean for all rows belonging to both buckets.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360