R嵌套用于循环和功能 - 保存数据

时间:2014-10-20 18:08:29

标签: r for-loop nested

我对R更新,我认为这可能是一个相当简单的问题。我创建了函数(min_find)来搜索来自传染病模型(df)的大数据框,以找到给定疫苗效力和疫苗成本的最低成本。这是功能代码。

# min find is a function that finds the percentage of vaccination associated with the optimal cost
# to use, source the code, then type min_find(n,x) in the console window
# replace n with 2 (80% efficacy), 3, 4, 5, 6 (100% efficacy)
# x is the disease to vaccination cost ratio - set this to whatever you want. 

min_find <- function(n,x) {
  n_sus <- df[m_range, n]
  n_inf <- df[m_range + 1*var + 1, n]
  n_rec <- df[m_range + 2*var + 2, n]
  n_vac <- df[m_range + 3*var + 3, n]

  vac_cost <- dis_cost / x

  cost_inf <- n_inf * dis_cost
  cost_rec <- n_rec * dis_cost
  cost_vac <- n_vac * vac_cost

  ppTC <- (cost_inf + cost_rec + cost_vac) / N
  find <- c(ppTC)
  min_cost <- paste("$",min(ppTC), sep = "")
  row_num <- paste(((which.min(find) - 1)/100),"%", sep="")
  results <- c(n, x, min_cost, row_num)
  print(results, digits = 4)
}

这是输出

[1] "2" "10"  "$655.393388415075" "81.09%"  

对于我的目的,min_find代码完美地工作(除了数字部分,对此的任何建议都很棒),但我希望能够一次分析多个场景。

为此,我创建了一个for循环。这是循环代码和输出:

for (n in c(2,3)){
  for (x in ratiotest){
    min_find(n, x)
  }
}

[1] "2"                 "10"                "$655.393388415075" "81.09%"           
[1] "2"                "15"               "$438.76247498737" "81.41%"          
[1] "3"                 "10"                "$655.393388415075" "76.32%"           
[1] "3"                 "15"                "$438.762446935463" "76.62%"        

循环运行得非常快,但是如果有一种方法可以使用应用函数来实现这一点,那也很棒。

我想要做的是保存数据框的所有结果,以便能够分析并可能进行一些绘图。我已经浏览了论坛,但仍然对如何解决这个问题感到迷茫。我想它可能相当直接,但任何帮助都会非常感激。如果在其他地方已经涉及这个问

谢谢!

0 个答案:

没有答案