Anna Rouw
Anna Rouw

Reputation: 99

Error with creating an ifelse function

So this is my code right now, I'm trying to create a function that will detect the words "DRUG COURT"

 drugcourt <- function(x) {
    ifelse(str_detect("DRUG COURT", print("TRUE"), print("FALSE")))
    }

And it's returning an error:

unused argument (print("FALSE"))

Any ideas? Thank you!

Upvotes: 0

Views: 410

Answers (2)

Jilber Urbina
Jilber Urbina

Reputation: 61154

No need to use ifelse since str_detect returns a logical vector. Also note that str_detect needs two argumments: string and pattern, in your code you did not provide such a string.

drugcourt <- function(x) {
  stringr::str_detect(x, "DRUG COURT")
}

> x <- c("dog", "shark", "DRUG COURT")
> drugcourt(x)
[1] FALSE FALSE  TRUE

You can even replace str_detect and use grepl("DRUG COURT", x) an R base function.

Upvotes: 3

stevec
stevec

Reputation: 52268

Remove print() - it's unnecessary in ifelse()

drugcourt <- function(x) {
  ifelse(str_detect(x, "DRUG COURT"), "TRUE", "FALSE")
}

drugcourt("HE WENT TO DRUG COURT")
# [1] "TRUE"

Upvotes: -1

Related Questions