rstringrstringi

Update the last occurrence of a word in a string only if certain condition is TRUE in R Programming


I have a dataframe with two character columns where I want to made the following changes

library(stringr)

Airport_ID <- c("3001","3002","3003","3004")

Airport_Name <- c("Adelaide Airport DTS", "Brisbane DTS Land Airport Land ADTS", "Washington DTS INC Airport DTS", "DALLAS Airport TDS INC")

df <- data.frame(Airport_ID,Airport_Name)

View(df)

Tried the below:


if (str_sub(df$Airport_Name,-nchar(" DTS")==" DTS") {

   stri_replace_last_fixed(df$Airport_Name," DTS"," DTSUpdated")

} else if (str_sub(df$Airport_Name,-nchar(" INC")==" INC") {
  
  stri_replace_last_fixed(df$Airport_Name," INC"," INCUpdated")

}

Getting the below error :

Error: unexpected '}' in "}"

Desired Output :

3001 Adelaide Airport DTSUpdated

3002 Brisbane DTS Land Airport Land ADTS

3003 Washington DTS INC Airport DTSUpdated

3004 DALLAS Airport TDS INCUpdated

Solution

  • 
    library(dplyr)
    library(stringr)
    
    
    Airport_ID <- c("3001", "3002", "3003", "3004")
    Airport_Name <- c(
        "Adelaide Airport DTS",
        "Brisbane DTS Land Airport Land ADTS",
        "Washington DTS INC Airport DTS",
        "DALLAS Airport TDS INC"
    )
    
    df <- data.frame(Airport_ID, Airport_Name)
    
    df %>%
        mutate(
            Airport_Name = case_when(
                str_extract(Airport_Name, "\\b(\\w+)$") == "DTS" ~
                    str_replace(Airport_Name, "\\b(\\w+)$", "DTSUpdated"),
                str_extract(Airport_Name, "\\b(\\w+)$") == "INC" ~
                    str_replace(Airport_Name, "\\b(\\w+)$", "INCUpdated"),
                TRUE ~ Airport_Name
            )
        )
    
    #>   Airport_ID                          Airport_Name
    #> 1       3001           Adelaide Airport DTSUpdated
    #> 2       3002   Brisbane DTS Land Airport Land ADTS
    #> 3       3003 Washington DTS INC Airport DTSUpdated
    #> 4       3004         DALLAS Airport TDS INCUpdated
    
    

    Created on 2022-07-07 by the reprex package (v2.0.1)