datazang
datazang

Reputation: 1169

Converting string into year-month in R?

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?

Upvotes: 1

Views: 89

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

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

Upvotes: 1

akrun
akrun

Reputation: 886938

Convert to Date class and use format

library(dplyr)
df <- df %>% 
     mutate(date = format(as.Date(date, '%Y%m%d'), '%Y-%m'))

Upvotes: 1

Related Questions