1

I want to convert the following string into year-month?

df <- tribble( ~date, '20201227', ) 

Here is the desired output.

new_df <- tribble( ~date, '2020-12', ) 

How can I do this?

2 Answers 2

1

Convert to Date class and use format

library(dplyr) df <- df %>% mutate(date = format(as.Date(date, '%Y%m%d'), '%Y-%m')) 
Sign up to request clarification or add additional context in comments.

Comments

1

Another possible option using gsub (but the as.Date answer by @akrun is more recommended)

transform( df, date = gsub("(\\d{4})(\\d{2}).*", "\\1-\\2", date) ) 

gives

 date 1 2020-12 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.