Dim(X) Must Have a Positive Length When Applying Function in Data Frame

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
1

1 Answer

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)
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest