I fixed the code, which had difficulies because y was a Factor variable. I created a function from the code. I still need to test its accuracy