I'm trying to apply this function to a data frame column:
best_recom <- function(x,n=1) {
y <- result2[x,order(-result2[x,])[n]]
inds = which(result2[x,] == y, arr.ind=TRUE)
recom <- names(inds[1])
return(recom)
}
Like this:
apply(last_visit[,2], 1, best_recom)
But I'm getting this error:
dim(X) must have a positive length
I already tried applying it as a matrix like this:
apply(as.matrix(last_visit)[,2],1,recomenda_n_melhor)
But I get the same error. These are the data frames that are used:
result2 - a similarity matrix - this is just a sample
X1.0 X1.1 X2.1 X3.1
X1.0 0.0000000 0.5000000 0.3872983 0.3162278
X1.1 0.5000000 0.0000000 0.2581989 0.0000000
X2.1 0.3872983 0.2581989 0.0000000 0.0000000
X3.1 0.3162278 0.0000000 0.0000000 0.0000000
last_visit
customer cat
1 1 X5.1
2 2 X6.1
3 3 X1.1
4 4 X2.1
dim() function in R Language is used to get or set the dimension of the specified matrix, array or data frame. Parameters: x: array, matrix or data frame.
The sapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of an array or matrix object. Since the sapply() function applies a certain operation to all the elements of the object it doesn't need a MARGIN.
It happens because R coerces last_visit[,2]
to a dimensionless vector, whereas apply
expects the object to have some dimensions. You can prevent the coercion by adding drop=F
to your command, i.e.:
apply(last_visit[,2,drop=F], 1, best_recom)
Another way would be just to use lapply
or sapply
on the vector:
lapply(last_visit[,2], best_recom)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With