Ido
Ido

Reputation: 211

if_else and str_c (tidyverse)

I have a column called "birth_year" with the last two digit of the year of birth: 64, 94, 92, 01 ... My goal is to transfer them into the full year of birth: 1964, 1994, 1992, 2001 ...

I could just use the function str_c("19", birth_year) but there are some years that are 2001, 2005.

I tried to use If_else but it seems not to work:

if_else(birth_year > 15, mutate(birth_year = str_c("19", birth_year)),mutate(birth_year = str_c("20", birth_year)))

the error I get is:

Error: condition must be a logical vector, not a spec_tbl_df/tbl_df/tbl/data.frame object.

how can I transform the last two digit of the year into the full year?

thanks, Ido

Upvotes: 0

Views: 392

Answers (3)

semaphorism
semaphorism

Reputation: 866

It's not particularly neater than the solutions already proposed, but lubridate can also be used:

library(lubridate)

birth_year <- c('65', '98', '01', '04', '99', '19')

year(parse_date_time2(birth_year, "y", cutoff_2000 = 30))

Results:

[1] 1965 1998 2001 2004 1999 2019

Just adjust cutoff_2000 as appropriate depending on your dataset.

Upvotes: 1

Karthik S
Karthik S

Reputation: 11584

Does thsi work for you:

library(dplyr)
st <- c('65', '98', '01', '04', '99', '19')
st
[1] "65" "98" "01" "04" "99" "19"
> ifelse(between(st,00,20), paste0('20',st), paste0('19',st))
[1] "1965" "1998" "2001" "2004" "1999" "2019"

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388972

You are using incorrect syntax. Try :

library(dplyr)
library(stringr)

df <- df %>%
        mutate(birth_year = if_else(birth_year > 15, 
                           str_c("19", birth_year),str_c("20", birth_year)))

Or a shorter way in base R :

df <- transform(df, birth_year = paste0(ifelse(birth_year > 5, 19, 20), birth_year))

Upvotes: 1

Related Questions