Generate subsequent month in R

Asked

Viewed 29 times

1

How do I place the following month?

df1
dt          nome idade
01/03/2018  ll    15
07/03/2019  dd    33
31/12/2019  ff    44

After rules

df1
dt          nome idade
01/03/2018  ll    15
01/04/2019  dd    33
01/01/2020  ff    44

The rule is as follows, if the day is different from "01" the same will have to have the day as "01" of the subsequent month, as df shows.

1 answer

2


Using the lubridate and dplyr packages:

library(lubridate)
library(dplyr)

#Criando o data.frame cedido. A função dmy converte para o formato data
df1 <- data.frame(dt = c(dmy("01/03/2018"), dmy("07/03/2019"), dmy("31/12/2019")),
                  nome = c("11", "ff", "dd"),
                  idade = c(15,33,44))

#O paste cria a data "01/mês/ano" da linha, %m+% adiciona o mês
#sem estourar a data limite do mês anterior, e months(1) a quantidade de mêses a serem somadas
df1 %>%
  mutate(dt2 = dmy(paste("01", month(dt), year(dt)))  %m+% months(1))          
dt nome idade        dt2
1 2018-03-01   11    15 2018-04-01
2 2019-03-07   ff    33 2019-04-01
3 2019-12-31   dd    44 2020-01-01

Browser other questions tagged

You are not signed in. Login or sign up in order to post.