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 |
>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