简体   繁体   中英

splitting values in a dataframe R

I have this data frame in R. name of df: POST

Order_id Postcalcode
1        5253HP
2        4261FF
44       5111QW

I want to split the numbers and the letters from the postal code because i only need the numbers so expected output is

Order_id Postalcode
1        5253
2        4261
44       5111
library(magrittr)
library(dplyr)
library(stringr)

df %>% mutate(Postcalcode = str_extract(Postcalcode,"\\d+"))

  Order_id Postcalcode
1        1        5253
2        2        4261
3       44        5111

Also, tidyr::separate may be worth looking at. In the example below the split is taking place at the defined position.

dta <- readr::read_table(file = "
Order_id Postcalcode
1        5253HP
2        4261FF
44       5111QW")

tidyr::separate(
    data = dta,
    col = "Postcalcode",
    into = c("first_part", "second_part"),
    sep = 4,
    remove = FALSE
)

Results:

# A tibble: 3 × 4
  Order_id Postcalcode first_part second_part
     <dbl> <chr>       <chr>      <chr>      
1        1 5253HP      5253       HP         
2        2 4261FF      4261       FF         
3       44 5111QW      5111       QW   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM