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

How can i convert a column based on a string pattern in R using tidyverse like functions?

I want to create two columns from the given below table DATA.I want the first column (say ID1) to have all the letters or numbers before the first "-" starting from left to right and the second column (ID2) to have the first letters or numbers before the first "-" starting from right to left and to print them as character.

val = c(1,2,3,4)
tor = c( "0001-NEW YORK , M.AVENUE, NY-U.S.A"  ,                                            
         "0023-cARAVAGGIO-MALTA"        ,                                              
         "009876-bUDAPEST-HUNGARY" ,NA)
DATA = tibble(val,tor)

the resulted table must look like this one :
| val | ID1 | ID2 |
|:—- |:——:| —–:|
| 1 | 0001 | U.S.A |
| 2 | 0023 | MALTA |
| 3 | 009876 | HUNGARY |
| 4 | NA | NA |

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

>Solution :

A possible approach using separate_wider_delim():

library(tidyverse)

val = c(1,2,3,4)
tor = c( "0001-NEW YORK , M.AVENUE, NY-U.S.A"  ,                                            
         "0023-cARAVAGGIO-MALTA"        ,                                              
         "009876-bUDAPEST-HUNGARY" ,NA)
DATA = tibble(val,tor)

DATA |> 
  separate_wider_delim(tor, delim = "-", names = c("ID1", "extra", "ID2")) |> 
  select(-extra)
#> # A tibble: 4 × 3
#>     val ID1    ID2    
#>   <dbl> <chr>  <chr>  
#> 1     1 0001   U.S.A  
#> 2     2 0023   MALTA  
#> 3     3 009876 HUNGARY
#> 4     4 <NA>   <NA>

Created on 2024-04-03 with reprex v2.1.0

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