Friday, 15 February 2013

r - Function not working in for loop -



r - Function not working in for loop -

kind of beginner question here: have function, cos.dissim i'm using compute dissimilarity between 2 vectors , works fine when phone call set value this:

doc.number = 1 cos.dissim(doc.matrix[doc.number, ], sk$prototype[sk$cluster[doc.number], ])

but when seek set in loop check 30 documents, code nothing. don't error message of kind, code doesn't output anything.

dissim.tot = function(){ for(x in 1:30){ doc.number = x cos.dissim(doc.matrix[doc.number, ], sk$prototype[sk$cluster[doc.number], ]) } }

am missing obvious here? i'm new language , haven't created many for loops.

for returns null, approach work, need assign outcome of each pass through loop object.

for example:

sqr <- function(x) x^2 # square x f <- function() { y <- numeric() # initialize output vector (i in 1:10) { y <- c(y, sqr(i)) # append square of y } return(y) } f() # [1] 1 4 9 16 25 36 49 64 81 100

that said, should work:

sapply(1:30, cos.dissim, doc.matrix[i, ], sk$prototype[sk$cluster[i], ])

r

No comments:

Post a Comment