0

I have a column with end dates and another column with number of days. I want to calculate start date from this information.

End dates: 7/15/2019; 6/10/2019
Number of days: 10; 9 I want to calculate Start date from the above information in R.

Watercayman
  • 7,970
  • 10
  • 31
  • 49
AKA
  • 3
  • 1
  • Hi @AKA, Welcome to Stack! Can you post a sample of your data using ```dput(head(df))``` (where ```df`` is the actual name of your dataframe? You've already got two good answers IMHO, but your actual data will allow testing too. Also, don't forget to read the help center section on [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers). tl:dr - If you feel like the answers below are valid (i.e. answered your question) please upvote them and make sure to also use the check next to the one that you feel best answers your question. – Russ Thomas Aug 10 '19 at 22:34
  • @AlessandroDaRugna I don't think this is *quite* a dupe of that one, since in that post they already have 2 dates, and need to calculate the difference between them, rather than subtracting some number of days from a date – camille Aug 10 '19 at 23:36

2 Answers2

2

The lubridate package provides functions to convert strings to Date (in this case, mdy). Then you can just subtract the number of days from the end date.

ed = c("7/15/2019", "6/10/2019")
n = c(10, 9)
lubridate::mdy(ed) - n
#[1] "2019-07-05" "2019-06-01"
Telepresence
  • 619
  • 2
  • 7
  • 22
1

Consider straightforward subtraction with base R:

df <- within(df, {
     end_date <- as.Date(end_date, format="%m/%d/%Y")
     start_date <- end_date - num_of_days
})
Parfait
  • 104,375
  • 17
  • 94
  • 125