使循环输出进入附加对象

时间:2019-07-08 08:38:35

标签: r for-loop output rbind

因此,我正在尝试制作基本的灵敏度分析脚本。通过添加到脚本末尾的打印,我可以根据需要输出输出。问题是我希望将所有输​​出附加在一起的小标题或对象可以导出为csv或xlsx。

我创建了两个函数,sens_analysis运行所有代码,multiple_across在表的每个可能的列中乘以每个可能的百分比。您需要multiple_across来运行sens_analysis。

我通常想要一个标题,但我只是添加了一个指标列,而不是可以进行排序。

我用mtcars制作了所有东西,因此应该很容易复制,问题是我的结尾处印有大量文字;不是我可以操纵或从中进行其他分析的对象。

我一直在尝试rbind,bind_row,以各种方式附加行。 或建立一个新对象。如您在第(18)行的代码中所见,我做了一些尝试填充的输出,效果不好。

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)

如果仅直接运行代码,则预期结果应该只是一堆打印的小物件,这些小物件不会出现在对象中。但是理想情况下,对于将来对数据的分析或易于使用,最好将输出汇总在一起。

1 个答案:

答案 0 :(得分:0)

因此我想出了办法,并将在此处添加我的答案,以防其他人遇到此问题。

我在循环中创建了一个列表,然后将这些列表绑定在一起。

仅关注右侧for循环之外的绑定行。

multiply_across<-function(data=data_select_weight,
  list=percent_to_1){
  varlist <- colnames(data[, -1])
  output_list <- list()
  for (i in varlist) {
    df1 <- data[,i]
    for (j in list) {
      name <- paste0(i, " BY ", (as.numeric(j)-1)*100, "% OVER ", disagg)

      df <- as_tibble(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))
      df<-df[,c(6,1,2,3,4,5)]


      output_list[[paste0(i," BY ",(as.numeric(j)-1)*100)]] <- (assign(paste0(i," BY ",(as.numeric(j)-1)*100,"% OVER ",disagg),df))

    }

  }

  bind_rows(lapply(output_list,
    as.data.frame.list,
    stringsAsFactors=F))

}