How to apply (or sapply) a function for double range of data?

时间:2016-03-02 10:51:47

标签: r sapply

I have this function

fun_2 <- function(x,L_inf,y){
  L_inf-((L_inf-y)/
            (exp(-B*(x-c(1:12))/12)))
}
B <- 0.5

The problem is similar this previous post R: How to create a loop for, for a range of data in a function? In this case i would to apply the fun_2 for this two range of data:

L_inf_range <- seq(17,20,by=0.1) #31 values
y_range <- seq(4,22,by=0.1)  # 19 values

I tried with:

sapply(L_inf_range, function(L) fun_2(12, L_inf=L,y_range))

but is not the expected output. My expected output is a new matrix genereted by sapply(or other kind of function) where the fun_2 is apply for all the value in L_inf_range and each time for all value of y_range.

Substantially it will be a matrix where fun_2 is apply for each values of L_inf_range(31 values) minus y_range (L_inf-y in fun_2) each time.

1 个答案:

答案 0 :(得分:0)

你也可以两次运行sapply来改变你的参数的顺序,使它更容易。

    fun_2_mod <- function(y, L_inf, x = X){ fun_2(x, L_inf, y)}

    sapply(y_range, function(Y){sapply(L_inf_range, fun_2_mod, y = Y)})

您可以将生成的列表列表绑定到一个数据框中。