[英]reference custom function in apply R
I have an N x 2 matrix called mat. 我有一个称为垫的N x 2矩阵。
mat <- cbind(c(2:4), c(.5, 1, 1.5))
colnames(mat) <- c('x2', 'x3')
I created a function called calcCDF in R. This function requires 3 inputs x1, x2, and x3. 我在R中创建了一个名为calcCDF的函数。此函数需要3个输入x1,x2和x3。 x1 defaults to 100000. The actual calcCDF function is more complicated.
x1默认为100000。实际的calcCDF函数更为复杂。 The one shown below is just to illustrate the point.
下面显示的内容只是为了说明这一点。
calcCDF <- function(x1=100000, x2, x3){
cdf <- x1 + x2 * x3
return(cdf)
}
calcCDF(x2=2, x3=0.5)
returns the value 100001 calcCDF(x2=2, x3=0.5)
返回值100001
I would like x2 and x3 to be populated with the first and second columns of mat respectively and apply the function to each row of mat so that I get back a vector of length N. 我希望x2和x3分别填充mat的第一和第二列,并将该函数应用于mat的每一行,以便获得长度为N的向量。
I tried apply(mat, 1, calcCDF(x2=mat[1], x3=mat[2]))
but get an error stating Error: unexpected ']'. 我尝试了
apply(mat, 1, calcCDF(x2=mat[1], x3=mat[2]))
但收到一条错误,指出错误:意外的']'。
If you want to use apply()
with your customised function calcCDF
, this is how you can use 如果要对您的自定义函数
calcCDF
使用apply()
,这是可以使用的方式
apply(mat, 1, function(y) calcCDF(x2 = y[1], x3 = y[2]))
OR 要么
apply(mat, 1, function(x) calcCDF(x2 = x["x2"], x3 = x["x3"]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.