0

I have dataframe that called df:

number       date
 1           2012-07-01
 2           2012-08-01
 3           2012-09-01
 4           2012-10-01
 5           2012-11-01

I need to subtract 3 month from every date. When I will run df it will give me that data frame:

number       date
 1           2012-04-01
 2           2012-05-01
 3           2012-06-01
 4           2012-07-01
 5           2012-08-01

What code do I need to write?

Bar Fichman
  • 19
  • 1
  • 1
  • 3
  • *Please*, for next time, read a little bit about [formatting questions](https://stackoverflow.com/editing-help). It might appear petty and/or just aesthetic, but when code blocks are displayed as html headers and blockquotes, it can be distracting. Further, adding `##` to each of your columns makes it onerous for us to try to use your data, where currently (after my edit), we can just highlight, copy, and run `read.table(header=TRUE, "clipboard")` (or similar for non-windows). – r2evans Jan 12 '21 at 16:47

1 Answers1

0

Using seq.Date.

d$date3 <- as.Date(sapply(d$date, seq, by="-3 month", length.out=2)[2,], 
                   origin="1970-01-01")
#   number       date      date3
# 1      1 2012-07-01 2012-04-01
# 2      2 2012-08-01 2012-05-01
# 3      3 2012-09-01 2012-06-01
# 4      4 2012-10-01 2012-07-01
# 5      5 2012-11-01 2012-08-01

Data:

d <- structure(list(number = 1:5, date = c("2012-07-01", "2012-08-01", 
"2012-09-01", "2012-10-01", "2012-11-01")), class = "data.frame", row.names = c(NA, 
-5L))
jay.sf
  • 60,139
  • 8
  • 53
  • 110