Skip to content

Instantly share code, notes, and snippets.

@sibyvt
Created May 14, 2016 07:41
Show Gist options
  • Save sibyvt/4b7c6006a48ab53187b33106c05a6bba to your computer and use it in GitHub Desktop.
Save sibyvt/4b7c6006a48ab53187b33106c05a6bba to your computer and use it in GitHub Desktop.
Selection: 14
|
| | 0%
| R has a special way of representing dates and times, which can be helpful if you're working with data that show how something changes over time (i.e. time-series
| data) or if your data contain some other temporal information, like dates of birth.
...
|
|==== | 3%
| Dates are represented by the 'Date' class and times are represented by the 'POSIXct' and 'POSIXlt' classes. Internally, dates are stored as the number of days since
| 1970-01-01 and times are stored as either the number of seconds since 1970-01-01 (for 'POSIXct') or a list of seconds, minutes, hours, etc. (for 'POSIXlt').
...
|
|========= | 6%
| Let's start by using d1 <- Sys.Date() to get the current date and store it in the variable d1. (That's the letter 'd' and the number 1.)
> d1 <- Sys.Date()
| You are quite good my friend!
|
|============= | 8%
| Use the class() function to confirm d1 is a Date object.
> class(d1)
[1] "Date"
| Excellent work!
|
|================= | 11%
| We can use the unclass() function to see what d1 looks like internally. Try it out.
> unclass(d1)
[1] 16935
| Great job!
|
|====================== | 14%
| That's the exact number of days since 1970-01-01!
...
|
|========================== | 17%
| However, if you print d1 to the console, you'll get today's date -- YEAR-MONTH-DAY. Give it a try.
> d1
[1] "2016-05-14"
| You are doing so well!
|
|=============================== | 19%
| What if we need to reference a date prior to 1970-01-01? Create a variable d2 containing as.Date("1969-01-01").
> d2 <-as.Date("1969-01-01")
| Excellent work!
|
|=================================== | 22%
| Now use unclass() again to see what d2 looks like internally.
> unclass(d2)
[1] -365
| Excellent job!
|
|======================================= | 25%
| As you may have anticipated, you get a negative number. In this case, it's -365, since 1969-01-01 is exactly one calendar year (i.e. 365 days) BEFORE 1970-01-01.
...
|
|============================================ | 28%
| Now, let's take a look at how R stores times. You can access the current date and time using the Sys.time() function with no arguments. Do this and store the result
| in a variable called t1.
> Sys.time()
[1] "2016-05-14 12:53:59 IST"
| Try again. Getting it right on the first try is boring anyway! Or, type info() for more options.
| t1 <- Sys.time() will store the current date and time in a variable called t1.
> t1 <- Sys.time()
| That's a job well done!
|
|================================================ | 31%
| View the contents of t1.
> t1
[1] "2016-05-14 12:54:37 IST"
| You are amazing!
|
|==================================================== | 33%
| And check the class() of t1.
> class(t1)
[1] "POSIXct" "POSIXt"
| Keep up the great work!
|
|========================================================= | 36%
| As mentioned earlier, POSIXct is just one of two ways that R represents time information. (You can ignore the second value above, POSIXt, which just functions as a
| common language between POSIXct and POSIXlt.) Use unclass() to see what t1 looks like internally -- the (large) number of seconds since the beginning of 1970.
> unclass(t1)
[1] 1463210677
| Excellent work!
|
|============================================================= | 39%
| By default, Sys.time() returns an object of class POSIXct, but we can coerce the result to POSIXlt with as.POSIXlt(Sys.time()). Give it a try and store the result
| in t2.
> t2 <- as.POSIXlt(Sys.time())
| Keep working like that and you'll get there!
|
|================================================================= | 42%
| Check the class of t2.
> t2
[1] "2016-05-14 12:56:20 IST"
| Not quite! Try again. Or, type info() for more options.
| Type class(t2) to view its class.
> class(t2)
[1] "POSIXlt" "POSIXt"
| You got it!
|
|====================================================================== | 44%
| Now view its contents.
> t2
[1] "2016-05-14 12:56:20 IST"
| Nice work!
|
|========================================================================== | 47%
| The printed format of t2 is identical to that of t1. Now unclass() t2 to see how it is different internally.
> unclass(t2)
$sec
[1] 20.75181
$min
[1] 56
$hour
[1] 12
$mday
[1] 14
$mon
[1] 4
$year
[1] 116
$wday
[1] 6
$yday
[1] 134
$isdst
[1] 0
$zone
[1] "IST"
$gmtoff
[1] 19800
attr(,"tzone")
[1] "" "IST" "IST"
| All that hard work is paying off!
|
|============================================================================== | 50%
| t2, like all POSIXlt objects, is just a list of values that make up the date and time. Use str(unclass(t2)) to have a more compact view.
> str(unclass(t2))
List of 11
$ sec : num 20.8
$ min : int 56
$ hour : int 12
$ mday : int 14
$ mon : int 4
$ year : int 116
$ wday : int 6
$ yday : int 134
$ isdst : int 0
$ zone : chr "IST"
$ gmtoff: int 19800
- attr(*, "tzone")= chr [1:3] "" "IST" "IST"
| Perseverance, that's the answer.
|
|=================================================================================== | 53%
| If, for example, we want just the minutes from the time stored in t2, we can access them with t2$min. Give it a try.
> t2$min
[1] 56
| Nice work!
|
|======================================================================================= | 56%
| Now that we have explored all three types of date and time objects, let's look at a few functions that extract useful information from any of these objects --
| weekdays(), months(), and quarters().
...
|
|============================================================================================ | 58%
| The weekdays() function will return the day of week from any date or time object. Try it out on d1, which is the Date object that contains today's date.
> weekdays(d1)
[1] "Saturday"
| You nailed it! Good job!
|
|================================================================================================ | 61%
| The months() function also works on any date or time object. Try it on t1, which is the POSIXct object that contains the current time (well, it was the current time
| when you created it).
> months(d1)
[1] "May"
| Not exactly. Give it another go. Or, type info() for more options.
| months(t1) will give you the current month.
> months(t1)
[1] "May"
| You got it right!
|
|==================================================================================================== | 64%
| The quarters() function returns the quarter of the year (Q1-Q4) from any date or time object. Try it on t2, which is the POSIXlt object that contains the time at
| which you created it.
> quarters(Q1-Q4)
Error in quarters(Q1 - Q4) : object 'Q1' not found
> quarters(t2)
[1] "Q2"
| All that practice is paying off!
|
|========================================================================================================= | 67%
| Often, the dates and times in a dataset will be in a format that R does not recognize. The strptime() function can be helpful in this situation.
...
|
|============================================================================================================= | 69%
| strptime() converts character vectors to POSIXlt. In that sense, it is similar to as.POSIXlt(), except that the input doesn't have to be in a particular format
| (YYYY-MM-DD).
...
|
|================================================================================================================= | 72%
| To see how it works, store the following character string in a variable called t3: "October 17, 1986 08:24" (with the quotes).
> t3: "October 17, 1986 08:24"
Error: object 't3' not found
> t3 <-"October 17, 1986 08:24"
| That's the answer I was looking for.
|
|====================================================================================================================== | 75%
| Now, use strptime(t3, "%B %d, %Y %H:%M") to help R convert our date/time object to a format that it understands. Assign the result to a new variable called t4. (You
| should pull up the documentation for strptime() if you'd like to know more about how it works.)
> strptime(t3, "%B %d, %Y %H:%M")
[1] "1986-10-17 08:24:00 IST"
| Not exactly. Give it another go. Or, type info() for more options.
| t4 <- strptime(t3, "%B %d, %Y %H:%M") will convert our date/time object to a format that R understands.
> t4 <- strptime(t3, "%B %d, %Y %H:%M")
| That's correct!
|
|========================================================================================================================== | 78%
| Print the contents of t4.
> t4
[1] "1986-10-17 08:24:00 IST"
| Nice work!
|
|============================================================================================================================== | 81%
| That's the format we've come to expect. Now, let's check its class().
> class(t4)
[1] "POSIXlt" "POSIXt"
| That's a job well done!
|
|=================================================================================================================================== | 83%
| Finally, there are a number of operations that you can perform on dates and times, including arithmetic operations (+ and -) and comparisons (<, ==, etc.)
...
|
|======================================================================================================================================= | 86%
| The variable t1 contains the time at which you created it (recall you used Sys.time()). Confirm that some time has passed since you created t1 by using the 'greater
| than' operator to compare it to the current time: Sys.time() > t1
> Sys.time() > t1
[1] TRUE
| All that practice is paying off!
|
|============================================================================================================================================ | 89%
| So we know that some time has passed, but how much? Try subtracting t1 from the current time using Sys.time() - t1. Don't forget the parentheses at the end of
| Sys.time(), since it is a function.
> Sys.time()-t1
Time difference of 12.29736 mins
| Excellent job!
|
|================================================================================================================================================ | 92%
| The same line of thinking applies to addition and the other comparison operators. If you want more control over the units when finding the above difference in
| times, you can use difftime(), which allows you to specify a 'units' parameter.
...
|
|==================================================================================================================================================== | 94%
| Use difftime(Sys.time(), t1, units = 'days') to find the amount of time in DAYS that has passed since you created t1.
> (Sys.time(), t1, units = 'days')
Error: unexpected ',' in "(Sys.time(),"
> difftime(Sys.time(), t1, units = 'days')
Time difference of 0.009145336 days
| You're the best!
|
|========================================================================================================================================================= | 97%
| In this lesson, you learned how to work with dates and times in R. While it is important to understand the basics, if you find yourself working with dates and times
| often, you may want to check out the lubridate package by Hadley Wickham.
...
|
|=============================================================================================================================================================| 100%
| Would you like to receive credit for completing this course on Coursera.org?
1: Yes
2: No
Selection: 1
What is your email address? [email protected]
What is your assignment token? vR2zUCocI0zuHsfK
Grade submission succeeded!
| That's a job well done!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment