I am trying to write a function which subsets a dataset containing a certain string.
Mock data:
library(stringr)
set.seed(1)
codedata <- data.frame(
Key = sample(1:10),
ReadCodePreferredTerm = sample(c("yes", "prefer", "Had refer"), 20, replace=TRUE)
)
User defined function:
findterms <- function(inputdata, variable, searchterm) {
outputdata <- inputdata[str_which(inputdata$variable, regex(searchterm, ignore_case=TRUE)), ]
return(outputdata)
}
I am expecting at least a couple of rows returned, but I get 0 when I run the following code:
findterms(codedata, ReadCodePreferredTerm, " refer") #the space in front of this word is deliberate
I realise I am trying to do something quite simple... but can't find out why it isn't working.
Note, the code works fine when not defined as a function:
referterms <- codedata[str_which(codedata$ReadCodePreferredTerm, regex(" refer", ignore_case=TRUE)), ]