0

I am trying to write a function which will give me simple descriptive statistics of a population by age and country.

Here is an example of my data:

popcount = 200:250
sex = rep(c("M", "F"), 25)
country = rep(c("NZ", "Aus", "Fiji", "PNG", "Samoa"), 10)

To get the aggregation, I have specified the following function

Aggregate_fun <- function(pop, ag1, ag2) {
popbylist <- data.frame(aggregate(pop, by = list(ag1, ag2)), FUN=sum)
return(popbylist)
}

Then I run this function on my data

Gend_Country <- Aggregate_fun(pop = popcount, ag1 = sex, ag2 = country)

When I run this, I get the following error message:

Error in match.fun(FUN) : argument "FUN" is missing, with no default

6. match.fun(FUN) 5. aggregate.data.frame(as.data.frame(x), ...) 4. aggregate.default(pop, by = list(ag1, ag2)) 3. aggregate(pop, by = list(ag1, ag2)) 2. data.frame(aggregate(pop, by = list(ag1, ag2)), FUN = sum) 1. Aggregate_fun(pop = popcount, ag1 = sex, ag2 = country)

I know there's an error with the way I am specifying the list of variables to aggregate by. I've tried a number of different things to fix this, but none of them work. Does anyone know how to write this function correctly?

1 Answer 1

2

Looks like a parenthesis is misplaced in that aggregate function placing the "FUN" outside of aggregate. Additionally popcount had 51 values while the other two only had 50. This code below is doing what I think you desire.

popcount = 201:250
sex = rep(c("M", "F"), 25)
country = rep(c("NZ", "Aus", "Fiji", "PNG", "Samoa"), 10)

Aggregate_fun <- function(pop, ag1, ag2) {
  popbylist <- data.frame(aggregate(pop, by = list(ag1, ag2), FUN=sum))
  return(popbylist)
}

Gend_Country <- Aggregate_fun(pop = popcount, ag1 = sex, ag2 = country)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.