Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I need to pick top 3 values from each column of a matrix using R and populate the values to a holder(another matrix).

While trying to do this, I am getting an error as :

Error in t.default(head(n = 3, rownames(trans.cosine[order(trans.cosine[,  : 
  argument is not a matrix

This is the R code i use:

recsys <- read.csv("H:/Recommender Systems/Recsys.csv") 
recsys.ibs <- (recsys[,!(names(recsys) %in% c("NAME"))])     
recsys.ibs.normalized <- normalize(recsys.ibs, byrow =  FALSE)
n <- recsys$NAME
trans <- t(recsys.ibs.normalized)
colnames(trans) <- n
trans.cosine <- cosine(trans)
write.csv(trans.cosine, "H:/Recommender Systems/cosine_similarity.csv")
recsys.neighbours <- matrix(NA, nrow=ncol(trans.cosine),ncol=3,dimnames=list(colnames(trans.cosine)))
for(i in 1:ncol(trans.cosine)) 
  recsys.neighbours[i,] <- (t(head(n=3,rownames(trans.cosine[order(trans.cosine[,i],decreasing=TRUE),][i]))))

I am getting the error as soon as i execute the above for loop.

I checked the vectors, they are matrix. But still i am getting the error.

> class(trans.cosine)
[1] "matrix"
> class(recsys.neighbours)
[1] "matrix"

Any help on this would be verymuch useful.

Thank you

@TimBiegeleisen - Thanks for your suggestion. I was checking each piece of the expression as you were suggesting, and converted the "trans.cosine" to a dataframe before getting into the for loop. It is working now. Thanks again. – Arun Nov 9, 2015 at 8:18

Your example is not reproducible, but because you are using [i] you get a single number which has no rownames, so that you get

t(NULL)
# Error in t.default(NULL) : argument is not a matrix

The same could happen without the [i] if the matrix has no rownames. And either way, rownames returns a vector, so using t is not meaningful here. head(3, is also odd, use [1:3]

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.