paste word with condition

name_type
apple-watch
apple-tablet
apple
apple-orange-watch
apple-orange-tablet
apple-orange

How do I add -laptop to the elements that don't end with -watch or -tablet? For example, row 3 would become apple-laptop ; row 6 would become apple-orange-laptop.

library(tidyverse)
tibble(
  name_type = c(
    "apple-watch", "apple-tablet", "apple",
    "apple-orange-watch", "apple-orange-tablet", "apple-orange"
  )
) -> toy_data
library(tidyverse)
suppressPackageStartupMessages({
  library(dplyr)
  library(stringr)
  }
)
tibble(
  name_type = c(
    "apple-watch", "apple-tablet", "apple",
    "apple-orange-watch", "apple-orange-tablet", "apple-orange"
  )
) -> toy_data

toy_data %>% mutate(name_type = ifelse(str_detect(name_type,"-") == FALSE,paste(name_type,"-laptop"),name_type))
#> # A tibble: 6 x 1
#>   name_type          
#>   <chr>              
#> 1 apple-watch        
#> 2 apple-tablet       
#> 3 apple -laptop      
#> 4 apple-orange-watch 
#> 5 apple-orange-tablet
#> 6 apple-orange

Created on 2020-08-06 by the reprex package (v0.3.0)

1 Like

Adding onto the earlier response the 6th row does not get the mutate since it already has the "-" and hence the ifelse fails.

Try the following

toy_data %>% mutate(name_type = ifelse(!stringi::stri_extract_last_words(name_type) %in% c("watch","tablet") ,paste0(name_type,"-laptop"),name_type))

Notice the "!" for negation and using stringi package for getting the last word and then checking against your keywords.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Thanks a lot @technocrat!

Just realized that the last row i.e. row 6 does not get the intended outcome.

library(tidyverse)
suppressPackageStartupMessages({
  library(dplyr)
  library(stringr)
}
)
tibble(
  name_type = c(
    "apple-watch", "apple-tablet", "apple",
    "apple-orange-watch", "apple-orange-tablet", "apple-orange"
  )
) -> toy_data

devices <- c("watch","tablet","laptop")

toy_data %>% mutate(name_type = ifelse(str_detect(name_type,"-") == FALSE ,paste0(name_type,"-laptop"),name_type)) %>%
  mutate(name_type = ifelse(str_detect(name_type,devices),name_type,paste0(name_type,"-laptop")))
#> # A tibble: 6 x 1
#>   name_type          
#>   <chr>              
#> 1 apple-watch        
#> 2 apple-tablet       
#> 3 apple-laptop       
#> 4 apple-orange-watch 
#> 5 apple-orange-tablet
#> 6 apple-orange-laptop

Created on 2020-08-06 by the reprex package (v0.3.0)

1 Like