【发布时间】:2019-07-08 08:38:35
【问题描述】:
所以我正在尝试制作一个基本的敏感性分析脚本。输出通过我添加到脚本末尾的打印输出。问题是我想要一个将所有输出附加在一起的小标题或对象,我可以将其导出为 csv 或 xlsx。
我创建了两个函数,sens_analysis 运行所有代码,和 multiply_across 乘以表中每个可能列的每个可能百分比。您需要 multiply_across 来运行 sens_analysis。
我通常想要一个标题,但我只是添加了一个指示列而不是我可以排序。
我用 mtcars 制作了所有东西,所以它应该很容易复制,问题是我最后只有一个巨大的印刷品;不是我可以操纵或从中提取以进行其他分析的对象。
我一直在尝试 rbind,bind_row,以各种方式附加行。 或者构建一个新对象。正如您在第 (18) 行的代码中看到的那样,我制作了一个名为 output 的东西,我试图填充它,但效果并不好。
rm(list = ls())
library(dplyr)
library(tidyr)
library(purrr)
library(tibble)
library(magrittr)
library(xtable)
data<-mtcars
percent<-c(.05,.1,.15)
goods<-c("hp","gear","wt")
weight<-c(6,7,8)
disagg<-"cyl"
func<-median
sens_analysis<-function(data=data, goods=goods, weight=weight, disagg=disagg, precent=percent, func=func){
output<-NULL%>%
as.tibble()
basket<-(rbind(goods,weight))
percent<-c(0,percent,(percent*-1))
percent_to_1<-percent+1
data_select<-data%>%
dplyr::select(c(goods,disagg))%>%
group_by_at(disagg)%>%
summarise_at(.vars = goods ,.funs = func)%>%
as_tibble()
data_select_weight<-purrr::map2(data_select[,-1], as.numeric(basket[2,]),function(var, weight){
var*weight
})%>% as_tibble %>%
add_column(data_select[,1], .before = 1)
colnames(data_select_weight)[1]<-disagg
multiply_across(data_select_weight,percent_to_1)
return(output)
#output2<-rbind(output2,output)
}
############################
multiply_across<-function(data=data_select_weight,list=percent_to_1){
varlist<-names(data[,-1])
for(i in varlist){
df1 = data[,i]
for(j in list){
df<-data
df[,i]<-round(df1*j,2)
df<-mutate(df, total = round(rowSums(df[,-1]),2))%>%
mutate(type=paste0(i," BY ",(as.numeric(j)-1)*100,"% OVER ",disagg))%>%
print(df)
#output<-bind_rows(output,df)
#output<-bind_rows(output,df)
#output[[j]]<-df[[j]]
}
}
}
##############################################################################################
sens_analysis(data,goods,weight,disagg,percent,func)
如果您直接运行代码,预期的结果应该只是一堆打印的小标题,它们不在对象中。但理想情况下,为了将来对数据进行分析或易于使用,最好将输出的表格附加在一起。
【问题讨论】: