Search code examples
rcase

how i can run case when with diferent nchar vector


I have this data frame. I need to substr fecha_nacimiento but it has 7 or 8 char.

fecha_nacimiento n
1011997 1
31122002 2

i try this

fecha_nacimiento <- fecha_nacimiento %>% 
  mutate(year = case_when(nchar(fecha_nacimiento$fecha_nacimiento == 7 ~ substr(fecha_nacimiento, 4, 7))),
                          nchar(fecha_nacimiento$fecha_nacimiento == 8 ~ substr(fecha_nacimiento, 5, 8))) 

But there is an error in MUTATE.

I wish to get the next formate

fecha_nacimiento n days month year
1011997 1 1 11 1997
31122002 2 31 12 2002

What i can do?


Solution

  • I think it's simpler to first make every sample in fecha_nacimiento to the same number of characters and then work from it. Also, if you are using dplyr, you don't need to specify the dataframe name inside the operations (fecha_nacimiento$fecha_nacimiento would be wrong).

    library(dyplr)
    
    fecha_nacimiento %>% # First, get every string to the same n characters
      mutate( ifelse(nchar(fecha_nacimiento) == 7, # if nchar 7
        paste('0',fecha_nacimiento,''), # add 0 to beginning
        fecha_nacimiento) %>% # or skip
      # Now the new colums
      mutate(
        day = substr(fecha_nacimiento, 1, 2),
        month = substr(fecha_nacimiento, 3, 4),
        year = substr(fecha_nacimiento, 5, 8)
      )