R:返回data.frame每行结果的函数

时间:2016-02-01 10:54:34

标签: r function loops while-loop dataframe

你好我是R的初学者,我正在尝试编写一个灵敏度分析函数,从样本“X”(每列有12列和2500个观察的数据表)返回一个名为Global的2500个值的向量成本(每行一个)。它确实工作正常,但问题是 j1,j2和j3 应该为每一行重新计算(对于while循环)用第一个“行”固定变量> 只有第一个结果实际上是正确的。

lcc<-function(X){
#initial costs
globalcost<-(X[,3]+X[,4]+X[,5]);       
#replacement costs 1
j1<-X[,6];
while(j1<30){globalcost<-globalcost+((X[,3]*((1/(1+((X[,2]-X[,1])/(1+X[,1]))))^j1)));j1<-j1+j1};        
#replacement costs 2
j2<-X[,7];
while(j2<=30){globalcost<-globalcost+((X[,4]*((1/(1+((X[,2]-X[,1])/(1+X[,1]))))^j2)));j2<-j2+j2};       
#replacement costs 3
j3<-X[,8];
while(j3<=30){globalcost<-globalcost+((X[,5]*((1/(1+((X[,2]-X[,1])/(1+X[,1]))))^j3)));j3<-j3+j3};       
#energy costs
globalcost<-globalcost+((5375.81*0.0507*X[,12])*((1-(1+((X[,2]-X[,1])/(1+X[,1])))^-30)/((X[,2]-X[,1])/(1+X[,1]))));        
#maintenance costs 1
globalcost<-globalcost+(X[,9]*((1-(1+((X[,2]-X[,1])/(1+X[,1])))^-30)/((X[,2]-X[,1])/(1+X[,1]))));         
#maintenance costs 1
globalcost<-globalcost+(X[,10]*((1-(1+((X[,2]-X[,1])/(1+X[,1])))^-30)/((X[,2]-X[,1])/(1+X[,1]))));        
#maintenance costs 3
globalcost<-globalcost+(X[,11]*((1-(1+((X[,2]-X[,1])/(1+X[,1])))^-30)/((X[,2]-X[,1])/(1+X[,1]))));     
#result
return(globalcost)}

我试图像这样创建'for循环'

lcc<-function(X){
for (i in 1:2500){
    #initial costs
    globalcost<-(X[i,3]+X[i,4]+X[i,5]);
    #replacement costs 1
    j1<-X[i,6];
    while(j1<30){globalcost<-globalcost+((X[i,3]*((1/(1+((X[i,2]-X[i,1])/(1+X[i,1]))))^j1)));j1<-j1+j1};
    #replacement costs 2
    j2<-X[i,7];
    while(j2<=30){globalcost<-globalcost+((X[i,4]*((1/(1+((X[i,2]-X[i,1])/(1+X[i,1]))))^j2)));j2<-j2+j2};
    #replacement costs 3
    j3<-X[i,8];
    while(j3<=30){globalcost<-globalcost+((X[i,5]*((1/(1+((X[i,2]-X[i,1])/(1+X[i,1]))))^j3)));j3<-j3+j3};
    #energy costs
    globalcost<-globalcost+((5375.81*0.0507*X[i,12])*((1-(1+((X[i,2]-X[i,1])/(1+X[i,1])))^-30)/((X[i,2]-X[i,1])/(1+X[i,1]))));
    #maintenance costs 1
    globalcost<-globalcost+(X[i,9]*((1-(1+((X[i,2]-X[i,1])/(1+X[i,1])))^-30)/((X[i,2]-X[i,1])/(1+X[i,1]))));
    #maintenance costs 1
    globalcost<-globalcost+(X[i,10]*((1-(1+((X[i,2]-X[i,1])/(1+X[i,1])))^-30)/((X[i,2]-X[i,1])/(1+X[i,1]))));
    #maintenance costs 3
    globalcost<-globalcost+(X[i,11]*((1-(1+((X[i,2]-X[i,1])/(1+X[i,1])))^-30)/((X[i,2]-X[i,1])/(1+X[i,1]))));}
    #risultato
return(globalcost)}

但在这种情况下,该函数仅为最后一行返回“globalcost”

然后我必须将此功能放在sobol x <- sobol(model = lcc, X1 = X1, X2 = X2, order = 2, nboot = 100)中以获得灵敏度分析

谢谢..!

1 个答案:

答案 0 :(得分:0)

我部分解决了添加

的问题
  • gc<-c()在“for loop”
  • 之前 循环中的
  • gc[i]<-c(globalcost)
  • return(gc)在“for loop”
  • 之后

但现在当我将我的功能作为敏感度分析中的模型时:x <- sobol(model = lcc, X1 = X1, X2 = X2, order = 2, nboot = 100)我收到此错误:

Error in colSums(d[, -1] * d[, 1]) : 
  'x' must be an array of at least two dimensions