Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change part of an entry by condition

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks in advance.

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading