3

我稍微修改了这个问题。

     integg <- function(t,a,b,con,s){   
  u <- ifelse(t - a < 0 ,0, t - a) 
  l <- ifelse(t - (a+b) < 0,0, t - (a+b))  
  s * integrate(Vectorize(function(foo,x){x}),lower=l,upper=u,x=con)      
}

这个方程会给我一个整数值,我有 3 个数组:As、Bs 和 Ss,它们代表参数“a”、“b”和“s”。

假设数组如下:

As <- seq(from=50,to=60,by=0.01)
Bs <- seq(from=130,to=140,by=0.01)
Ss <- seq(from=0.0001,to=0.01,by=0.0001)
# con is a constant
con <- 55
# I have 7 values for t and I want to do one at a time, 
# so for this example I have t=360
t <- 360
# although I'll want to do also for my other values c(0,20,40,60,120,240)

我的最终目标是测试这些数组 As、Bs 和 Ss 的每一个组合。我一直在尝试使用外部,但之后循环失败。

# first make one array w/ all possible combinations
all_poss <- outer(As,Bs,paste)
# now include the third array
all_poss <- outer(all_poss,Ss,paste)

head(all_poss)
> [1] "50 130 1e-04"    "50.01 130 1e-04" "50.02 130 1e-04" 
  [4] "50.03 130 1e-04" "50.04 130 1e-04" "50.05 130 1e-04"


    ### I would have to change my integg function a little bit, to deal w/ the pasted items
      integg2 <- function(t,con,all){  
    a <- strsplit(h,split=' ')[[1]][1]
    b <- strsplit(h,split=' ')[[1]][2]
    s <- strsplit(h,split=' ')[[1]][3]   

    u <- ifelse(t - a < 0 ,0, t - a) 
    l <- ifelse(t - (a+b) < 0,0, t - (a+b))  
    s * integrate(Vectorize(function(foo,x){x}),lower=l,upper=u,x=con)   
}

     ### I would then need to loop integg2() somehow through my list of all possibilities

      all_vals <- sapply(all_poss,integg2)
      # I haven't gotten this to work, but i'm not sure this is 
      # even an efficient way to do what I want

最后我需要某种循环,如果有人对如何组合这些数组的所有可能性以及更有效的循环方式有任何更好的想法,请告诉我。

任何帮助都会很棒!

4

1 回答 1

1

该函数expand.grid将创建一个数据框,其中包含您输入的向量/因子的所有组合。另一种方法是使用带有 `data.table 的连接。

integrate返回一个列表;您可能需要使用$value.

我还根据个人喜好更改了变量名称(而且我不喜欢名称与内置函数如 重叠t)。

av <- seq(from=50,to=60,by=0.01)
bv <- seq(from=130,to=140,by=0.01)
sv <- seq(from=0.0001,to=0.01,by=0.0001)
tv <- c(seq(from=0,to=60,by=20),seq(from=120,to=360,by=120))
con <- 55

##method 1: using built-in functions (warning: can be slower and memory-intensive)
cmb <- expand.grid(list(av=av,bv=bv,sv=sv,tv=tv))
cmb <- within(cmb,{
    u <- ifelse(tv - av < 0 ,0, tv - av)
    l <- ifelse(tv - (av+bv) < 0,0, tv - (av+bv))
    value <- sv * mapply(function(...){integrate(...)$value},
        lower=l,upper=u,
        MoreArgs=list(f=Vectorize(function(x,constant){constant}),constant=con))
})

##method 2: using package data.table (for speed and efficient memory use)
dt.av <- data.table(av,k=1,key="k")
dt.bv <- data.table(bv,k=1,key="k")
dt.sv <- data.table(sv,k=1,key="k")
dt.tv <- data.table(tv,k=1,key="k")
cmb <- dt.av[dt.bv[dt.sv[dt.tv]]] #joins together
cmb[,u := ifelse(tv - av < 0 ,0, tv - av)]
cmb[,l := ifelse(tv - (av+bv) < 0,0, tv - (av+bv))]
cmb[,value:=mapply(function(...){integrate(...)$value},
    lower=l,upper=u,
    MoreArgs=list(f=Vectorize(function(x,constant){constant}),constant=con)
)]
于 2012-08-31T19:24:06.320 回答