0

Please before make it as duplicate read carefully my question!

I am new in R and I am trying to figure it out how to calculate the sequential date difference from one row/variable compare to the next row/variable in based on weeks and create another field/column for making a graph accordingly.

There are couple of answer here Q1 , Q2 , Q3 but none specifically talk about making difference in one column sequentially between rows lets say from top to bottom.

Below is the example and the expected results:

Date        Var1 
2/6/2017    493
2/20/2017   558
3/6/2017    595
3/20/2017   636
4/6/2017    697
4/20/2017   566
5/5/2017    234

Expected

Date    Var1    week
2/6/2017    493 0
2/20/2017   558 2
3/6/2017    595 4
3/20/2017   636 6
4/6/2017    697 8
4/20/2017   566 10
5/6/2017    234 12
Community
  • 1
  • 1
Dan Art
  • 3
  • 1

1 Answers1

0

You can use a similar approach to that in your first linked answer by saving the difftime result as a new column in your data frame.

# Set up data
df <- read.table(text = "Date        Var1 
                 2/6/2017    493
                 2/20/2017   558
                 3/6/2017    595
                 3/20/2017   636
                 4/6/2017    697
                 4/20/2017   566
                 5/5/2017    234", header = T)
df$Date <- as.Date(as.character(df$Date), format = "%m/%d/%Y")

# Create exact week variable
df$week <- difftime(df$Date, first(df$Date), units = "weeks")

# Create rounded week variable
df$week2 <- floor(difftime(df$Date, first(df$Date), units = "weeks"))

df                   
# Date        Var1 week            week2
# 2017-02-06  493  0.000000 weeks  0 weeks
# 2017-02-20  558  2.000000 weeks  2 weeks
# 2017-03-06  595  4.000000 weeks  4 weeks
# 2017-03-20  636  6.000000 weeks  6 weeks
# 2017-04-06  697  8.428571 weeks  8 weeks
# 2017-04-20  566 10.428571 weeks 10 weeks
# 2017-05-05  234 12.571429 weeks 12 weeks
MeetMrMet
  • 1,349
  • 8
  • 14