1

I have data of dates chosen from csv excel file and it has the format of day/month/year

DateAchat=DataAch[which((nchar(as.character(DataAch$FrontOfficeUser_ld))==5)),"CreationDate"]

    head(DateAchat)
    [1] 07/03/2015 07/03/2015 07/03/2015 07/03/2015 07/03/2015 08/03/2015

Then, I want to add 30 days to the first date for example. I get no correct result

as.Date(DateAchat[1])+30
[1] "0007-04-19"

I didn't understand why I get like this??

  • It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data. (such as a `dput()` for example) so we can see what the class of the variables you are working is since that makes a big difference. – MrFlick Oct 31 '17 at 14:36
  • 1
    Because you use the default date format of Year/Month/Day, and 30 days after March 20, 0007 is April 19, 0007. – Gregor Thomas Oct 31 '17 at 14:40
  • the class of my data is a facor. –  Oct 31 '17 at 14:43

3 Answers3

2

You need to convert your character column into Date column with the correct format.

    as.Date("07/03/2015", format="%d/%m/%Y") + 30
    [1] "2015-04-06"
isandeep
  • 46
  • 1
0

Try this:

DateAchat<-as.Date(DateAchat, format = "%d/%m/%Y")
DateAchat[1]+30

I suppose that the variable DateAchat are strings in each date.

Henry Navarro
  • 943
  • 8
  • 34
0

You can do more than days with the lubridate package.

library(lubridate)
as.Date("07/03/2015", format="%d/%m/%Y") + duration(30, 'days')
as.Date("07/03/2015", format="%d/%m/%Y") + duration(30, 'hours')
troh
  • 1,354
  • 10
  • 19
  • It's a little bit confusing because sometimes we have dates, sometimes posixct, sometimes we need to use +days(30) , sometimes +ddays(30) – skan May 08 '21 at 11:02