dim(X) must have a positive length when applying function in data frame

后端 未结 1 1634
天命终不由人
天命终不由人 2021-02-14 07:43

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(result         


        
1条回答
  •  南方客
    南方客 (楼主)
    2021-02-14 08:08

    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)
    

    0 讨论(0)
提交回复
热议问题