rdplyrsplit

How to split a number into its digits in R


new here so forgive me if this sounds dumb.

I am currently working on a project, the data set has a variable that consists of two digits. For example 12 or 34. The second digit is from 1 to 5 and I need to isolate this one. There are round about 18 000 observations so doing this manually is not an option for me.

I tried the seperate function from dplyr.

demog %>% separate(socioEcon, c("A", "B"))

I also tried a couple of other things which I already deleted.

How would you guys try to split the data?


Solution

  • demog <- data.frame(socioEcon = c(12,34))
    
    library(dplyr)
    demog |>
      mutate(socioEcon = as.character(socioEcon)) |>
      tidyr::separate(socioEcon, c("A", "B"), sep = 1, remove = F)
    
    
      socioEcon A B
    1        12 1 2
    2        34 3 4