R365: Day 32 – Formatting dates

R365: Day 32 – Formatting Dates

I recently had to work with a dataset that I had put together in Excel that was poorly formatted. The dataset had date values associated with it but Excel had formatted them in an odd way. Luckily, R is really flexible in what it accepts as dates and lets you tell it what format everything is in.

#set your working drive (change this to whatever you need)
setwd('L:/Robin/R')
## open up your datasheet
## I just made a random datasheet with dates and some random data
spore=read.csv(file="R365.csv", head=TRUE, sep=',')
##look at your data
spore
spore.date=as.Date(spore$date,format='%m/%d/%Y')
spore.date
##now coerce it into a time series with {zoo}
require(zoo)
sporeproblem=zoo(spore$spore.number,spore.date)
##now you can work with it like its a time series dataset
plot(sporeproblem)

You can use the as.Date() function to format your dates pretty easily. The codes for what to use to represent days, months, years, days of the week, etc are available here and are reprinted below for convenience:

Symbol Meaning Example
%d day as a number (0-31) 01-31
%a
%A
abbreviated weekday
unabbreviated weekday
Mon
Monday
%m month (00-12) 00-12
%b
%B
abbreviated month
unabbreviated month
Jan
January
%y
%Y
2-digit year
4-digit year
07
2007
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s