R:如何为函数中的一系列数据创建循环? [英] R: How to create a loop for, for a range of data in a function?
问题描述
我有此参数:
L_inf <- seq(17,20,by=0.1)
和此功能:
fun <- function(x){
L_inf*(1-exp(-B*(x-0)))}
我将在L_inf
值范围内应用此功能.
我尝试使用循环for
,如下所示:
I would to apply this function for a range of value of L_inf
.
I tried with loop for
, like this:
A <- matrix() # maybe 10 col and 31 row or vice versa
for (i in L_inf){
A[i] <- fun(1:10)
}
Bur R回应:longer object length is not a multiple of shorter object length
.
我的预期输出是一个矩阵(或数据帧或列表),其中每个向量L_inf
的值(长度= 31)有10个结果(fun(1:10)
).
该怎么办?
Bur R respond: longer object length is not a multiple of shorter object length
.
My expected output is a matrix (or data frame, or list maybe) with 10 result (fun(1:10)
) for each value of the vector L_inf
(lenght=31).
How can to do it?
推荐答案
您正在尝试将10个元素的向量放入一个矩阵单元中.您想将其分配给矩阵行(您可以使用A[i,]
访问第i行).
You are trying to put a vector of 10 elements into one of the matrix cell. You want to assign it to the matrix row instead (you can access the ith row with A[i,]
).
但是在这种情况下使用for循环效率低下,并且使用"apply"功能之一非常简单. Apply
函数通常返回一个列表(这是用途最广泛的容器,因为基本上没有约束).
But using a for loop in this case is inefficient and it is quite straightforward to use one of the "apply" function. Apply
functions typically return a list (which is the most versatile container since there is basically no constraint).
此处sapply
是Apply函数,它试图 S 将其结果放大为方便的数据结构.在这种情况下,由于所有结果的长度都相同(10),因此sapply
会将结果简化为矩阵.
Here sapply
is an apply function which tries to Simplify its result to a convenient data structure. In this case, since all results have the same length (10), sapply
will simplify the result to a matrix.
请注意,我修改了您的函数以使其显式依赖于L_inf.否则,它将无法执行您认为应该做的事情(如果您需要更多信息,请参见关键字"closures").
Note that I modified your function to make it explicitly depend on L_inf. Otherwise it will not do what you think it should do (see keyword "closures" if you want more info).
L_inf_range <- seq(17,20,by=0.1)
B <- 1
fun <- function(x, L_inf) {
L_inf*(1-exp(-B*(x-0)))
}
sapply(L_inf_range, function(L) fun(1:10, L_inf=L))
这篇关于R:如何为函数中的一系列数据创建循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!