Home > Net >  Change part of an entry by condition
Change part of an entry by condition

Time:07-03

I want to remove/change the wording in a cell, if a certain condition in another column is true. My df looks somehow like this:

Route mode
train - car - train first mile
car - plane - train main mile
train - plane - car first mile
car first mile

So if the mode is first mile I want to change "train" into "public transport" otherwise nothing should happen.

I tried it with df$Route <- ifelse(df$Route == "*train*" & df$mile=="first/last mile" , "public transport", df$Route) but nothing happened.

I am new to R and pretty lost, so I appreciate any help.

Thanks in advance.

CodePudding user response:

You could use gsub in an ifelse where you replace train with public transport:

df <- data.frame(Route = c("train - car - train", "car - plane - train", "train - plane - car", "car"),
                 mode = c("first mile", "main mile", "first mile", "first mile"))


df$Route <- with(df, ifelse(mode == "first mile", gsub("train", "public transport", Route), Route))
df
#>                                       Route       mode
#> 1 public transport - car - public transport first mile
#> 2                       car - plane - train  main mile
#> 3            public transport - plane - car first mile
#> 4                                       car first mile

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

  • Related