-1

I have a column in a dataset filled with dates, and I'd like to replace them with week values. Is there a way to set a specific span of dates (January 1, 2016 to January 7th, 2016, for example) and each time any date within that range appears to replace it with another value (Week 1, for example). Thank you for any help!

Below is the dataset I'm working on:

Text   Date        
Text 1 2016-02-05 10:55:00
Text 2 2016-02-09 10:56:28
Text 3 2016-02-18 20:40:33


Desired output:

Text   Date        
Text 1 Week 1
Text 2 Week 2
Text 3 Week 3
Claire
  • 135
  • 2
  • 11
  • It depends on your dates variable, if your date is within a single year, you can use the `week()` function in `lubridate` package to get the week number. But if it is across multiple years, you need to do something like `cut` to convert. – Psidom May 15 '16 at 01:35
  • The weeks are weeks in a semester. They start at end of January and run until now, 12 in total. Does that impact things? – Claire May 15 '16 at 01:37
  • As long as it is within a year, you can use `week()` function. – Psidom May 15 '16 at 01:39

2 Answers2

0

Best to use lubridate's wday. First of install it if you don't have it:

install.packages("lubridate")

As a simple example:

library(lubridate)
mydate <- as.Date("2016-02-05 10:55:00", format = "%Y-%m-%d")
wday(mydate)

PS: 1 is Sunday.

To do it for the whole column:

dat$Week <- wday(
  as.Date(dat$Date, format = "%Y-%m-%d")
)

If this answers your question kindly mark it as a solution &/or up-vote it.

user10853
  • 302
  • 1
  • 4
  • 17
0

Following the clarifications in the comments, this code should yield the expected output:

SemStartWeek <- 5 #variable introduced to avoid obscure "magic numbers" in code
df1$Date <- paste("Week",as.numeric(strftime(df1$Date),"%W")) - SemStartWeek + 1)
#    Text   Date
#1 Text 1 Week 1
#2 Text 2 Week 2
#3 Text 3 Week 3

data

df1 <- structure(list(Text = structure(1:3, .Label = c("Text 1", "Text 2", 
               "Text 3"), class = "factor"), Date = structure(1:3, 
               .Label = c("2016-02-05 10:55:00", "2016-02-09 10:56:28", 
               "2016-02-18 20:40:33"), class = "factor")), .Names = c("Text",  
                "Date"), class = "data.frame", row.names = c(NA, -3L))
RHertel
  • 23,412
  • 5
  • 38
  • 64
  • That's week of the year. I think they want week of the month if I am not mistaken – Rich Scriven May 15 '16 at 01:31
  • These are weeks in a semester. So there are 1-12 and they start at the end of January. – Claire May 15 '16 at 01:38
  • @Claire Thanks for the clarification; I updated the code accordingly. It does not check whether the date that is provided falls into the semester, so the output is not necessarily limited to "Week 1" to "Week 12". Exception handling to treat cases of invalid data is easy to introduce in the code, but seems to be beyond the scope of this question. – RHertel May 15 '16 at 08:16
  • 1
    Thanks so much! This is great. – Claire May 15 '16 at 14:25