I am new to R and programming. I have a set of ratings for 45000 users and 40 odd movies. I need to predict new ratings for each user based on their pearson correlation with other users. I also need to store the set of similar users for each user-movie combination.The code that I have managed to write is this
# Matrix of users and ratings
x <- matrix(rnorm(1:100), nrow = 10 , ncol = 30)
df = list()
# correlation matrix
cor_mat <- cor(x)
# similarity limits
upper = 1
lower = 0.4
# empty matrix to store predicted values
final_x = matrix(NA,nrow = 10,ncol = 30)
for (i in 1:ncol(x)){
for( j in 1:nrow(x)){
sim_user = which(cor_mat[i,] >= lower & cor_mat[i,] < upper)
final_x[i,j] = t(x[sim_user,j]) %*%
cor_mat[sim_user,j]/sum(cor_mat[sim_user,j])
df[[length(df)+1]] = cbind.data.frame(i,j,sim_user,cor_mat[sim_user,j])
}
}
Questions:
- I am looping over each element of the matrix which works fine but seems pretty novice to me. Can something better be done?
- I have heard of the foreach package but read that it adds value only when a single operation takes a long time to execute which is not the case here. Will it still provide me good performance?
x
square in your example? More generally, is itm-by-n
wherem
is the number of movies andn
is the number of users? Note thatcor(x)
will ben-by-n
so the first loop (i
) should be iterating over1:ncol(x)
, not1:nrow(x)
. So your code will likely break with more realistic data. \$\endgroup\$df
is not initialized so it won't run as-is. Please make sure you provide a reproducible example; which means you should be able to run without error from a fresh session. Then try to makex
a non-square matrix to reveal the problem I was describing in my comment. Then please edit your question with the corrected code. \$\endgroup\$