What is an alternative to passing a variable to a regular expression in R?
r, regex, variables
Solution
Use `paste` to concatenate the strings to create the pattern:
removeByLength<- function(text,lowerCutOff=2,upperCutOff=12){
pattern <- paste("\\b[a-zA-Z0-9]{1,",lowerCutOff,
"}\\b|\\b[a-zA-Z0-9]{",upperCutOff,",}\\b", sep="")
text <- gsub(pattern, " ", text)
return(text)
}
Problem
My piece of code to remove short & long words from some text is: ``` # Remove Words based on lowerCutOff & upperCutOff removeByLength<- function(text,lowerCutOff=2,upperCutOff=12){ text<- gsub("\\b[a-zA-Z0-9]{1,lowerCutOff}\\b|\\b[a-zA-Z0-9]{upperCutOff,}\\b"," ",text) return(text) } ``` How can I achieve the needed functionality without hardcoding the lower & upper cutoffs?