Unable to update values in a column based on pattern match of another column in a dataframe in R

I have a dataframe in R which has two columns Machine Name(character) and Region(factor).They have values as follows(few examples):

Machine Name Region
1233.corp.pdo.om APAC
xyz.om Europe
345.corp.pdo.cm Europe
abc12.cm Americas

So i want to update the region with pdo for the machines which have corp.pdo in them.But when i am trying to update its not happening using if else.Can you please help.

Something like this?

library(dplyr, warn.conflicts = FALSE)
library(stringr)

df <- tribble(~ `Machine Name`, ~ Region,
              "1233.corp.pdo.om", "APAC",
              "xyz.om", "Europe",
              "345.corp.pdo.cm", "Europe",
              "abc12.cm", "Americas")

mutate(df, Region = if_else(str_detect(`Machine Name`, "corp.pdo"), "pdo", Region))
#> # A tibble: 4 x 2
#>   `Machine Name`   Region  
#>   <chr>            <chr>   
#> 1 1233.corp.pdo.om pdo     
#> 2 xyz.om           Europe  
#> 3 345.corp.pdo.cm  pdo     
#> 4 abc12.cm         Americas

Created on 2020-07-20 by the reprex package (v0.3.0)

Yes like this only.Let me try this.Hope this works.I will update you.Thanks.

I get the following error:

Error: false must be a character vector, not a factor object

Its got to do with Region column i guess which is a factor type.

Indeed. I missed the part where you stated that Region is a factor. The simplest workaround is to coerce it into a character vector. You can always convert it back to factor later with pdo added as a new level if necessary.

df %>% 
  mutate(Region = as.factor(Region)) %>% 
  mutate(Region = if_else(str_detect(`Machine Name`, "corp.pdo"), "pdo", as.character(Region)))
#> # A tibble: 4 x 2
#>   `Machine Name`   Region  
#>   <chr>            <chr>   
#> 1 1233.corp.pdo.om pdo     
#> 2 xyz.om           Europe  
#> 3 345.corp.pdo.cm  pdo     
#> 4 abc12.cm         Americas

I tried doing that.Although it doesn't throw any error but it doesn't update the values for those records.
Code:-

df3_machine_region %>%mutate(Region= ifelse(str_detect(Machine.Name, "corp.pdo"), "pdo", as.character(Region)))

Output:(sample)
Machine Name Region
D120710.corp.pdo.om
Europe

D120867.corp.pdo.om
Americas

Not sure about that. It would help if you could post a self-contained reproducible example with a subset of your data.

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