Trying to create function using grepl to replace a word in a string.
Airport_ID<-c("3001","3002","3003","3004")
Airport_Name<-c("Adelaide Airport GOODFIND","GOODFIND DTS Land Airport Land ADTS",
"Washington DTS INC GOODFINDAirport DTSUpdated",
"DALLAS Airport TDS GOODFIND")
TF_Data<-data.frame(Airport_ID,Airport_Name)
Created the below function
STR_Manip_F_M_L_V1 <- function(data=NULL,by_text1="GOODFIND",by_text2="Updated") {
if(!require(glue)) {library(glue) }
TFD <- TF_Data %>%
filter(grepl(glue("^{by_text1} "),Airport_Name) |
grepl(glue(" \\({by_text1}\\) "),Airport_Name) |
grepl(glue(" \\({by_text1}\\$"),Airport_Name) )
TFD$Airport_Name <- str_replace(TFD$Airport_Name = glue("^{by_text1} "),replacement = glue("^{by_text2} ") )
return(TFD)
}
Error :
Error: object 'TFD' not found.
CodePudding user response:
Several problems here:
You define
data
in the function arguments but useTFD_Data
. This is not causing an error but is a logical mistake, making reproducibility and troubleshooting a bit more difficult.Your use of
str_replace
is not quite right, don't "name" the arguments as you've done here. (Or ... perhaps just change your=
to a comma ...).
Since you're using dplyr
earlier, I think it's good to stay in that mode ... try this:
STR_Manip_F_M_L_V1 <- function(data=NULL,by_text1="GOODFIND",by_text2="Updated") {
out <- data %>%
filter(grepl(glue("^{by_text1} "),Airport_Name) |
grepl(glue(" \\({by_text1}\\) "),Airport_Name) |
grepl(glue(" \\({by_text1}\\$"),Airport_Name) ) %>%
mutate(Airport_Name = str_replace(Airport_Name, paste0("^", by_text1), by_text2))
out
}
STR_Manip_F_M_L_V1(TF_Data)
# Airport_ID Airport_Name
# 1 3002 Updated DTS Land Airport Land ADTS