Leremi13
Leremi13

Reputation: 25

R - Problem : Mutate doesn't create a new column

I have a dataframe with 2 variables : ID and Date of Delivery. What i intend to do is grouping the dataframe by ID, then to add one month+i to the date of delivery with "i" being the nth occurence of the same ID. An example:

ID   Date.Delivery   New.Date
001   2020-01-01    2020-02-01 (+1 month)
001   2020-01-01    2020-03-01 (+2 months, as there is a 2nd occurence of the same ID)
002   2020-01-01    2020-02-01 (+1 month, as this is the first occurence of a new ID)

In order to achieve this i try this code :

DF <- DF %>%
      group_by(ID) %>%
      mutate(New.Month = for(i in 1:n()) {DF$Date.Delivery[i] %m+% months(0+i)})

It's seems to work, as it gives me the new dates as number. The problem is that it doesn't create a new column in the DF. Indeed, when i call DF$New.Month the message "Unknown Columns : "New.Month"" appears. Then when i view the DF, at the end there is a sort of data.frame or list instead of the new column with :

-attr(*, "groups")=Classes 'tbl_df' , 'tbl' and 'data.frame': 1791 obs. of 2 variables :
..$ Num.Contrat: chr "001" "002" "003" ....
..$ .rows: List of 1791
.. ..$ : int 15205
.. ..$ : int 16190 16191 16192 16193 16194
.. ..$ : int 5989 5990 5991
.. 
[... 20 lines omitted]

I try to figure it out why my code doesn't create a new column as mutate should do.

Thanks for your help

Upvotes: 2

Views: 1509

Answers (1)

Martin Gal
Martin Gal

Reputation: 16998

Hi there and welcome to SO. Using dplyr this should give you the desired output:

df %>%
  group_by(ID) %>%
  mutate(New.Month = Date.Delivery %m+% months(row_number(ID)))

# A tibble: 3 x 3
# Groups:   ID [2]
#    ID    Date.Delivery New.Month 
#    <chr> <date>        <date>    
# 1 001   2020-01-01    2020-02-01
# 2 001   2020-01-01    2020-03-01
# 3 002   2020-01-01    2020-02-01

Upvotes: 2

Related Questions