Quarterly Date in a Data Frame - r

I have a dataframe that is structured as such
Date Value Variable
However, the date in my data is quarterly, read in from a .csv in the form 2000 Q1, etc.
As such, my normal method of converting dates:
mychart11$Date <- as.Date(mychart$Date , "%d/%m/%y")
mychart11[order(mychart$Date),]
does not work because there is no %q option for quarterly.
I'm aware I could create quarterly dates from the data using the zoo package, but I need them to be in the dataframe, because I need to plot the dates using ggplot later using code like
geom_line(data=mychart, aes(Date, value, group="Date", colour="Total"),
position=position_dodge(1)) + scale_x_date(labels = date_format("%b"))
and because the date is a factor, I get the error message
Invalid input: date_trans works with objects of class Date only
Any help is much appreciated.

You can use zoo to convert your data to class yearqtr and then use as.Date() (from the zoo package...it is actually as.Date.yearqtr()) to convert to a regular date.
mychart11$Date <- as.Date(as.yearqtr(mychar$Date),frac=0)
Notice that frac=0 will create a resulting date that is at the beginning of said quarter. Use frac=1 to get the end of the quarter. In between values are also permitted, though I can't think they would be common.

Related

Research panel analysis in R

I am a newbie to Stackoverflow, stats and R, so apologies for the simple nature of my question/request for advice:
I am completing analysis of a large data-set comprising of 2 files: a txt containing internal temperature data and a second SPSS data file.
To kick off, I have exported the SPSS data into CSV format and stripped back to contain just the few columns i think i need - house type and occupant type. I have imported all the temperature data and merged the two using a common identifier.
So now I have a merged data frame, containing all the data i need (to begin with) to start completing some analysis.
First question: I have year, date and time as separate columns. However the time column has imported with an incorrect date before "30/12/1899". How can i delete the date part of all observations from this column, but retain the time?
Second question Similar to above, the date colum shows the correct date, but has the time following, which is not correct (every observation showing 00:00:00), how can I delete all the times from this column?
Third question How can I combine the correct Time with correct date, to end up with DD/MM/YYYY HH:MM:SS
Fourth question Should i create subsets of merged to facilitate the analysis: ie: each house type (seperate subsets) vs temp, time and occupant type?
Dates can be brought in as they are instead of factor via the parameter as.is = TRUE i.e.
data <- read.csv(choose.files(), as.is = T)
I would try reading the csv file again and then working with the date time. It will come in as a chron or some format like that and you'll need to change it to Posixct, well I do anyway. To view help on a function, type question mark followed by function name i.e. ?as.posixct.
Date.Time: chron "2018/08/04 10:10:00", ... # '%Y-%m-%d %H:%M:%S' current format as read in from my system.
# Date format you want is '%d/%m/%Y %H:%M'
# tz='' is an empty time zone can't remember exactly you probably should read up on
# finally on the left side of the assign <- I am creating a new column Date.
# You can over write the old column, Date.Time, but can't hurt to learn how to delete
# a column.
data$Date <- as.POSIXct(date$Date.Time, tz='', '%d/%m/%Y %H:%M:%S')
# Now remove the original column. -Date.Time take out Date.Time, if you leave the
# minus out, the data will contain the subset Date.Time and no other columns.
data <- subset(data, select = -Date.Time)
Try this first, and I will look into removing time with in a date field. I have an idea, but I'd rather see if this helps with the problem first.
Though if you do want to merge the Year, month, day columns, you could try something like this, seem like a logical thing to do, you can always keep the original format and delete it later. It's not hurting anything.
data$YMD <- paste(data$Year," ",
data$Month, " ",
data$Day)
Also while you are at it. Install a library called dplyr, written by the same guy that did ggplot2, Hadley....
install.packages("dplyr")
# The add it to the top of your file like ggplot.
library(dplyr)

Convert Dates from a Data Frame from Numeric into Date Format in R (produces NAs)

I'm a Rookie with R. I have read in a Data Frame from Excel in R with the read.csv2 call, (Converted the Excel-file into csv).
I changed every Date in the table to a Y-M-D Format and wanted to use:
lapply(df$dates, as.Date, Format = "%Y/%m/%d")
but it produces NAs for every Date then.
When i ask for the mode it says the Dates are "numeric".
I tried to convert into character before into Dates with:
lapply(df$dates, as.character)
I dont know why it producs the NAs. Can someone help?
If you want to avoid the pain of finding the good format, there is dataPreparation package which provide a function to do that easily.
require(dataPreparation)
df <- setColAsDate(df, cols = "dates")
It will try to guess the format among thousand of various formats.
(NB: Please note that I'm the developer of this package.)

Specify output of as.Date without the year (R)

I am trying to convert a vector of factors into a vector of dates. The data is formatted as month/date (e.g. 5/20, 4/13, 11/11). I want to retain the format but need to change the data type from factor to date.
df$date <- as.Date(df$date, format = '%m/%d')
Is what I have at the moment. What is returned is 2017-5-20 or 2017-4-13 for example. My question is, is there a way to have as.Date not return the year? Additionally, is there a way to do this in lubridate that may be more efficient? I would like my output to return 5-20 or 4-13. All examples I find online always include the year and seem to leave my question unanswered.

Having difficulty with the start argument for ts( ). Losing date formatting

First, new to programming.
I built a table with 3 columns and I want to evaluate based on time series, so I'm playing around with the ts() function. The first column of my table is DATE as.date in the format "yyyy-mm-dd". I have one observation per variable per day. I've apply ts() to the table and tried start=1 (first observation?) and checked head(df) and the DATE column is sending back loose sequence of numbers that I can't identify (12591, 12592, 12593, 12594, 12597, 12598).
Could it be that the as.date is messing things up?
The line I use is:
ts(dy2, start=1, frequency= 1)
I've also been playing with the deltat argument. In the help file it suggests 1/12 for monthly data. Naturally, I tried 1/365 (for daily data), but have yet to be successful.
As suggested by G. Grothendieck you can use the zoo package. Try this:
require(zoo)
dates <- as.Date(dy2[,1], format = "%Y-%m-%d")
x1 <- zoo(dy2[,2], dates)
plot(x2)
x2 <- zoo(dy2[,3], dates)
plot(x1)
If this does not work, please provide further details about your data as requested by MrFlick. For example, print the output of dput(dy2) or at least head(dy2).

R chart by date

I've got transactional data from a SQL query which I turn into a data frame. The first column of the df contains UNIX timestamps (format="%Y/%d/%m %H:%M") which I would like to use to create a graphics plot using par to display 1 unique lineplot per date. At the moment I am fumbling around with splitting column 1 and comparing with previous row to look for a change then assigning a dummy indicator to use in my plot command.
Thanks,
Will
Somewhat hard to answer without any example data but I'll take a shot.
I'm guessing your date looks like this: "2009-03-04 17:45"
It's probably being read as character. You can verify the class of each column of your data frame by running str(data.frame)
Using package stringr, you can just read the y/d/m and convert that to a Date class like so:
library(stringr)
date="2009-03-04 17:45"
date=as.Date(str_replace_all(str_sub(date,3,10),"-","/"), "%y/%d/%m")
You can then use date as a group in ggplot2 to plot one line per date. You could also create separate panels (one per date) using + facet_wrap(~date) in your ggplot call.
start by just getting the date part from your timestamp
SELECT *,DATE(timestampcolumn) as thedate FROM yourtable;
Convert date column to factor
mydf <- transform(mydf,as.factor(thedate))
Plot it with e.g. xyplot
library(lattice)
xyplot(varx~vary|thedate,data=mydf)

Resources