Home > OS >  R: How to keep only desired word from the string?
R: How to keep only desired word from the string?

Time:10-21

From the URL column I need keep word "export" or "import" if it exist in the string

df <- data.frame (URL  = c("export-180100-from-ec-to-us", "import-420340-to-ir-from-es","export","Product"), X = c(100,200,50,600))

                          URL   X
1 export-180100-from-ec-to-us 100
2 import-420340-to-ir-from-es 200
3                      export  50
4                     Product 600

Expected output

    URL    X
1 export   100
2 import   200
3 export   50
4 Product  600

CodePudding user response:

Use sub from base R where by replace 0 or more characters after - with empty string, ie -.* is replaced by ''

transform(df, URL = sub('-.*','',URL))

      URL   X
1  export 100
2  import 200
3  export  50
4 Product 600
  • Related