1

I have a custom function that I have built that takes two inputs, does some processing to compute a value and return it.

Now, I want to use specific columns of a dataframe as inputs to this custom function. I want the function to process each row of the dataframe column and compute the corresponding return value. I do not want to use a FOR loop to iterate through each row of the dataframe. I have tried the "apply" function - but, do not seem to have any luck getting it to work.

This is a illustration of what I have outlined above.

Myfunction(movie, user)
{
    do some processing with the input values
    return(predict_value)
}

Pred_rating<-apply(Mydataset[,c("Movie_ID","User_ID")],MARGIN = 1,Myfunction)

If the computation of the function performed as expected, assuming the Movie_id and User_ID columns had 5 rows each for example, I would expect the result of "apply" to be a vector of 5 values; as the apply function has computed a return value for each of row of the input.

Questions:

Am I coding the "apply" function correctly? Is there a different delivered/packaged function I should be using?

dhilmathy
  • 2,800
  • 2
  • 21
  • 29

1 Answers1

0

If your function support vectorized inputs, you can compute it with the following

Pred_rating <- Myfunction(Mydataset$Movie_ID, Mydataset$User_ID)

and no need for for-loop.

Otherwise I suggest to look into Map and mapply. See this for details.