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
match.fun(FUN)出错:缺少参数“FUN”,没有默认值
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)
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 个解决方案
#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.
看起来括号在该聚合函数中放错了位置,将“FUN”置于聚合之外。另外popcount有51个值,而另外两个只有50个。下面的代码正在做我认为你想要的。
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)
#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.
看起来括号在该聚合函数中放错了位置,将“FUN”置于聚合之外。另外popcount有51个值,而另外两个只有50个。下面的代码正在做我认为你想要的。
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)