简体   繁体   English

R中带有用户定义函数的apply()

[英]apply() in R with user defined function

I try to use the apply function using my own function. 我尝试通过自己的函数使用apply函数。 However, I keep getting this error: Error in match.fun(FUN) : 'calculate_3month_average_volume(volume_matrix, 90)' is not a function, character or symbol 但是,我不断收到此错误:match.fun(FUN)中的错误:'calculate_3month_average_volume(volume_matrix,90)'不是函数,字符或符号

Code below: 代码如下:

#Calculate 3 monthtly average volume (does not work, coding issue)

calculate_3month_average_volume <- function(stock, number_of_days){

return(SMA(stock, number_of_days)) 
}



avg_volume_matrix <- apply(X = volume_matrix, MARGIN = 2, FUN =    calculate_3month_average_volume(volume_matrix,90))
avg_volume_matrix <- apply(volume_matrix,2,function(x){
  SMA(x,90) #can also be return(SMA(x,90))
  })

Should also do the trick as you don't have to call the function into your environment to begin with. 也应该做到这一点,因为您不必首先将函数调用到环境中。

The issue you are having specifically is that within your apply loop when you state "FUN= calculate_3month_average_volume(volume_matrix,90)", you should match your arguments in the called function with respect to x, as apply(x=,MARGIN=,FUN=,...) . 您具体遇到的问题是,当您声明“ FUN = calculate_3month_average_volume(volume_matrix,90)”时,您应该在Apply循环中将您的参数与x进行匹配,因为apply(x=,MARGIN=,FUN=,...) If we were using a function that was called into the environment as you have, we would use: 如果我们使用的函数像您在环境中那样被调用,我们将使用:

avg_volume_matrix <- apply(volume_matrix,2,calculate_3month_average_volume(x,90))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM