【发布时间】:2017-03-24 10:54:26
【问题描述】:
我对 R 中的函数没有经验。我正在尝试构建一个通过目标变量计算平均值的函数(在我的示例中:funded_final)。
我的数据:
residential_status funded_final
Living with parents 0
Rent 0
Rent 0
Own 1
Own 0
Own 0
Rent 0
Rent 0
Rent 0
Living with parents 0
Rent 0
Rent 0
Rent 1
当我在函数之外执行此操作时,效果很好
test2 %>% group_by(residential_status) %>%
summarise(tar_average = round((mean(funded_final, na.rm=TRUE))*100,2),N = n()) %>% arrange(desc(tar_average)) %>% mutate(Perc = round((N/sum(N))*100,2),Cum_Perc = cumsum(Perc))%>% print(n = nrow(.))
结果:
residential_status tar_average N Perc Cum_Perc
<fctr> <dbl> <int> <dbl> <dbl>
1 Own 33.33 3 23.08 23.08
2 Rent 12.50 8 61.54 84.62
3 Living with parents 0.00 2 15.38 100.00
当我使用该函数时,我只得到总平均值:
group.by.func <- function(dataframe,target){ dataframe %>%group_by(residential_status) %>%
summarise(tar_average = round((mean(target, na.rm=TRUE))*100,2),N = n()) %>%
arrange(desc(tar_average)) %>%
mutate(Perc = round((N/sum(N))*100,2),Cum_Perc = cumsum(Perc))%>%
print(n = nrow(.))}
group.by.func(test2,test2$funded_final)
结果:
residential_status tar_average N Perc Cum_Perc
<fctr> <dbl> <int> <dbl> <dbl>
1 Living with parents 15.38 2 15.38 15.38
2 Own 15.38 3 23.08 38.46
3 Rent 15.38 8 61.54 100.00
提前致谢!
【问题讨论】: