Reputation: 177
I want to automatise a code that calculates transport times. I would like that the code gives me 4 months that you can choose out of a big readout from a year and splits up the last month in its four weeks and just describes the data subsets (describing is not the problem).
Generating subsets from a dataset for chosen months is not the problem because I can define the months. But where I struggle is the 3/4 weeks of the last month. I need to identify them automatically and after that generate the subsets. (I hope that generating subsets should be easier after identifying.)
I can give you a little mock-up of my data.
dates <- as.Date(c("2019-01-07", "2019-01-08", "2019-01-09",
"2019-01-15", "2019-01-21"))
number <- c(12,13,14,15,20)
df <- data.frame(number, dates)
The original df contains of 60 variables but I believe this simple mockup can provide enough info for the task.
I am pretty new to r, I have no idea how to solve the problem, I will show you how I solved it with the months, but as said, in this case they are defined.
function(data = df, m1 = "01" , m2 = "02") {
Monat1 <- subset(data, format.Date(dates , "%m") == m1)
Thank you for helping me out a bit.
Upvotes: 0
Views: 58
Reputation: 1443
You can do it using base R and lubridate
dates <- as.Date(c("2019-01-07", "2019-01-08", "2019-01-09",
"2019-01-15", "2019-01-21"))
number <- c(12,13,14,15,20)
df <- data.frame(number, dates)
str(df)
library(lubridate)
df$condition <- ifelse(month(df$dates) == month(Sys.Date())-1,week(df$dates),"-")
condition will check if the date is less than a month ago or not and if yes it will give you week number for that particular value
Upvotes: 0
Reputation: 978
you can use the function strftime
strftime(df$dates, format = "%W")
in rstudio use
?strftime()
to see all the different values you can extract from a date or POSIXCT object
Upvotes: 3