Reputation: 3502
In my analysis, I have to extract the day of a week and the day number of each fortnight from Date objects. I want the result to look like below
Date weekday fortnightly
2010-05-01 Saturday 1
2010-05-02 Sunday 2
.
.
2010-05-14 Friday 14
2010-05-15 Saturday 1
2010-05-16 Sunday 2
.
.
2010-05-28 Friday 14
2010-05-29 Saturday 1
2010-05-30 Sunday 2
2010-05-31 Monday 3
2010-06-1 Tuesday 4
2010-06-2 Wednesday 5
I extracted the weekday as below
df$weekday <- weekdays(as.Date(df$Date))
However, I don't know which function I can use to extract the day number for each fortnight.
Any suggestions would be appreciated.
Upvotes: 1
Views: 379
Reputation: 887891
We can try
(seq_along(v1)-1)%%14 + 1L
#[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 2 3 4 5 6 7 8 9 10 11
#[26] 12 13 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 2 3 4 5 6 7 8
#[51] 9 10 11 12 13 14 1 2 3 4
v1 <- seq(as.Date('2010-05-01'), length.out=60, by = '1 day')
Upvotes: 2
Reputation: 389275
Is this what you want?
Taking @akrun's data as reference
v1 <- seq(as.Date('2010-05-01'), length.out=60, by = '1 day')
c(rep(seq(1, 14, 1), floor(length(v1)/14)), 1:(length(v1)%%14))
# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 2 3 4
# [33] 5 6 7 8 9 10 11 12 13 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 2 3 4
Repeating a sequence of numbers from 1 to 14 for length(v1)/14
times and then appending the remaining numbers.
So if in your case it's a data frame then you can try,
c(rep(seq(1, 14, 1), floor(nrow(df)/14)), 1:(nrow(df)%%14))
which would again generate the same sequence.
Upvotes: 2