1

I try to use the apply function using my own function. 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

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))
Jolien .A
  • 173
  • 3
  • 18
  • Try: `apply(X = volume_matrix, MARGIN = 2, FUN = calculate_3month_average_volume, volume_matrix, 90)` – Gopala Jan 27 '16 at 21:54
  • @user3949008 This gives me error: Error in FUN(newX[, i], ...) : unused argument (90) – Jolien .A Jan 27 '16 at 21:56
  • 2
    Oooops...volume matrix is already an argument. So, you should just pass the number_of_days = 90. Take a look at this: http://stackoverflow.com/questions/14427253/passing-several-arguments-to-fun-of-lapply-and-others-apply – Gopala Jan 27 '16 at 22:00

1 Answers1

1
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=,...). 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))
TJGorrie
  • 386
  • 3
  • 13