Your problem is that great doesn't have direct antonyms. If you look up great in WordNet Search, you will see that all antonyms are indirect via some other word. You'd have to first go over the similar to relationships, and look up for antonyms there. On the contrary, happy has a direct antonym (opposed to).
You might want to catch this specific error with a tryCatch
:
antonyms <- function(x){
filter <- getTermFilter("ExactMatchFilter", x, TRUE)
terms <- getIndexTerms("ADJECTIVE", 5, filter)
synsets <- getSynsets(terms[[1]])
related <- tryCatch(
getRelatedSynsets(synsets[[1]], "!"),
error = function(condition) {
message("No direct antonym found")
if (condition$message == "RcallMethod: invalid object parameter")
message("No direct antonym found")
else
stop(condition)
return(NULL)
}
)
if (is.null(related))
return(NULL)
return(sapply(related, getWord))
}