0

Kind of a beginner question here: I have a function, cos.dissim that I'm using to compute the dissimilarity between two vectors and it works fine when I call it by itself with a set value like this:

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

But when I try to put it in a loop to check all 30 documents, the code does nothing. I don't get an error message of any kind, the code just 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 I missing something obvious here? I'm new to the language and Haven't created many for loops.

2
  • 1
    Do you just want to print the result? If so, then wrap your command in print(cos.dissim(...)). When you're inside of a loop automatic printing is disabled (which is usually what you want anyway) Commented Oct 23, 2014 at 5:46
  • I'm trying to get all the results into a matrix but thank you for letting me know this. I thought the loop wasn't working at all but now I'm seeing the results. Commented Oct 23, 2014 at 5:51

1 Answer 1

1

for returns NULL, so for your approach to work, you need to assign the outcome of each pass through the loop to an object.

For example:

sqr <- function(x) x^2 # square x

f <- function() {
  y <- numeric() # initialize the output vector
  for (i in 1:10) {
    y <- c(y, sqr(i)) # append the square of i to y
  }
  return(y)
}

f()

#  [1]   1   4   9  16  25  36  49  64  81 100

That said, something like this should also work:

sapply(1:30, cos.dissim, doc.matrix[i, ], SK$prototype[SK$cluster[i], ])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.