Change the date in R and put it into condition - r

If have two columns with dates in my dataset. Now I want them to have the same format. The first one looks like this: yyyymmdd (so, January 1st 2015 is 20150101) and the second one looks like this: dd/mm/yyyy (so, January 1st 2015 is 01/01/2015). Anyone who can help me with that?
Because after that I want to have a condition that a third column gives the value 1 if the year of both dates are the same or if one is earlier than the other one.
Hope anyone can help me out!

Here is how we could solve this:
We could use parse_date_time() function from lubridate package. It is important to use the orders argument as desired so what is first year or month etc.. and
all should be wrapped around ymd() to get date without hours and minutes:
library(tibble)
# example data
df<- tibble( x_date = "20150101",
y_date= "01/01/2015")
library(lubridate)
library(dplyr)
df %>%
mutate(across(contains("date"), ~ymd(parse_date_time(., orders = c('ymd', 'dmy')))))
x_date y_date
<date> <date>
1 2015-01-01 2015-01-01

Related

How can I show Q1 to quarter without year on r

I am studying R and the exercise needs that I create a column to Quarter where the data seem Q4.
I use zoo library and lubridate, but the result that I achieved was a year plus Q1.
I have a column InvoiceDate where I it has a complete datetime.
What I need:
The original table, more specifically column, has a date-time like this: 2010-12-01 08:26:00. The column name is InvoiceDate. I need to get this column and to create other columns with specific values, like a quarter, year, month, etc.
What I archieved:
How do I achieve my goal?
You can use the inbuilt functions to extract the information that you need.
library(dplyr)
df %>%
mutate(quarter = quarters(InvoiceDate),
Month = format(InvoiceDate, '%b'),
weekday = weekdays(InvoiceDate))

Converting string to date in R returns NAs

I have a column of my dataframe as
date
17-Feb
17-Mar
16-Dec
16-Nov
16-Sep
17-Feb
I am trying to convert it into a date column from string. I am using the following pieces of code:
as.Date(df$Date, format="%y-%b")
and
as.POSIXct(df$Date, format="%y-%b")
Both of them give NAs
I am getting the format from this link
The starting number is year. Sorry for the confusion.
I assume from your approach that the 17 and 16 refer to the year 2017 and 2016 respectively. You need to also specify the day of month. If you don't care about it, then set it to the 1st.
A slight modification to your code will work, by appending '-01' to the date then updating your format argument to reflect this:
df = data.frame(Date = c("17-Feb", "17-Mar", "16-Dec"))
as.Date(paste0(df$Date, "-01"), format="%y-%b-%d")

Converting variables in form of "2015M01" to date format in R?

I have a date frame df that simply looks like this:
month values
2012M01 99904
2012M02 99616
2012M03 99530
2012M04 99500
2012M05 99380
2012M06 99103
2013M01 98533
2013M02 97600
2013M03 96431
2013M04 95369
2013M05 94527
2013M06 93783
with month that was written in form of "M01", "M02"... and so on.
Now I want to convert this column to date format, is there a way to do it in R with lubridate?
I also want to select columns that contain one certain month from each year, like only March columns from all these years, what is the best way to do it?
The short answer is that dates require a year, month and day, so you cannot convert directly to a date format. You have 2 options.
Option 1: convert to a year-month format using zoo::as.yearmon.
library(zoo)
df$yearmon <- as.yearmon(df$month, "%YM%m")
# you can get e.g. month from that
months(df$yearmon[1])
# [1] "January"
Option 2: convert to a date by assuming that the day is always the first day of the month.
df$date <- as.Date(paste(df$month, "01", sep = "-"), "%YM%m-%d")
For selection (and I think you mean select rows, not columns), you already have everything you need. For example, to select only March 2013:
library(dplyr)
df %>% filter(month == "2013M03")
Something like this will get it:
raw <- "2012M01"
dt <- strptime(raw,format = "%YM%m")
dt will be in a Posix format. The strptime function will assign a '1' as the default day of month to make it a complete date.

R aggregate by %Y-%b as date

I have a data frame item_sold_time with a item_sold_time$SaleDate "POSIXct" "POSIXt" column, looking like this 2015-04-28 07:59:43.
I want to aggregate by month in year:
df2<-aggregate(list(Qty=item_sold_time$Qty), by=list(ISBN=item_sold_time$ISBN,DateYM=strftime(item_sold_time$SaleDate, format="%Y-%b")), FUN=sum)
The problem with strftime is that it converts the date into characters and I get an error if I try to convert it back into date.
I tried all combinations of date formatting, I could find in 2 days of searching. The final destination of that date is to be used in this plot:
ggplot(df2, aes(x = DateYM, y=Qty))
Please help. Thanks
Set each date to (e.g.) the 15th of the month, then can aggregate by date and plot as normal.
as.Date(format(item_sold_time$SaleDate, "%Y-%m-15"))

R: Creating two date variables from a complete date

I have date recorded as: Month/Day/Year or MM/DD/YYYY
I would like to write code that creates two new variables from that information.
I would like a year variable alone
I would like to create a quarter variable
The Quarter Variables would not be influenced by year. I would want this variable to apply to all years.
Quarter 1 would be January 1 - March 31
Quarter 2 would be April 1 - June 30
Quarter 3 would be July 1 - September 30
Quarter 4 would be October 1 - December 31
Any assistance would be greatly appreciated. I cannot seem to get the nuance of how to do these functions in R.
Thanks,
Jared
Assuming that the date variable is of class POSIX** you could do:
#example date
date <- as.POSIXlt( "05/12/2015", format='%m/%d/%Y')
In order to return the year from a date data.table has already a function to do it and that is year:
library(data.table)
> year(date)
[1] 2015
As for the quarter it can easily be created from the function below (uses data.table::month that returns the number of a month):
quarter <- function(x) {
rep(c('quarter 1','quarter 2','quarter 3','quarter 4'), each=3)[month(x)]
}
> quarter(date)
[1] "quarter 2"
Using only the base packages:
Try formatting your dates with the strptime fxn, so that all dates are now in the Year-Month-Day format. This format constrains the each element of the date to be the same character length and in the same position. Look at the strptime documentation for the appropriate formatting argument.
date.vec<-c(1/1/1999,2/2/1999)
fmt.date.vec<-strptime(date.vec, "%m/%d/%Y")
With the dates in this format it is easy to extract the year, month, and day using the substring function
Year<-substring(fmt.date.vec,1,4)
Month<-substring(fmt.date.vec,6,7)
Day<-substring(fmt.date.vec,9,10)
With this information you can now generate your Quarter vector any number of ways. For example if a data.frame "df" has a Month column:
df$Quarter<-"Quarter_1"
df[df$Month %in% c("04","05","06"),]$Quarter<-"Quarter_2"
df[df$Month %in% c("07","08","09"),]$Quarter<-"Quarter_3"
df[df$Month %in% c("10","11","12"),]$Quarter<-"Quarter_4"

Resources