<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/r-weekly-bulletin-vol-vi/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.quantinsti.com/blog/r-weekly-bulletin-vol-vi/"> R programming</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><img sizes="(max-width: 1200px) 100vw, 1200px" alt="" class="wp-image-8385" src="https://i1.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/Weekly-R-Bulletin_6.jpg?w=450&ssl=1" data-recalc-dims="1"></p>
<p>This week’s R bulletin will cover topics like how to parse milliseconds in R, how to format dates and method to extract specific parts of date and time. </p>
<div></div>
<p>	<a data-link="https://twitter.com/share?text=Learn+some+interesting+R+programming+functions.+%40QuantInsti&amp;url=https://www.quantinsti.com/blog/r-weekly-bulletin-vol-vi/" target="_blank" rel="nofollow" href="https://twitter.com/share?text=Learn+some+interesting+R+programming+functions.+%40QuantInsti&url=https://www.quantinsti.com/blog/r-weekly-bulletin-vol-vi/"><span><span>We will also cover functions like %within%, %m+%, to.period function, period.max and period.min functions. </span><span>Click To Tweet<i></i></span></span></a>Hope you like this R weekly bulletin. Enjoy reading!</p>
<h3>Shortcut Keys</h3>
<p>1. Indent – hit Tab button at beginning of the line<br>
2. Outdent – Shift+Tab<br>
3. Go to a specific line – Shift+Alt+G</p>
<h3>Problem Solving Ideas</h3>
<h4>How to parse milliseconds in R</h4>
<p>When R reads dates from a text or spreadsheet file, it will typically store them as character vector or a factor. To convert them to dates, we need to parse these strings. Parsing can be done using the strptime function, which returns POSIXlt dates.</p>
<p>To parse the dates, you must tell strptime which bits of the string correspond to which bits of the date. The date format is specified using a string, with components specified with a percent symbol followed by a letter. See the example below. These components are combined with other fixed characters, such as colons in times, or dashes and slashes in dates to form a full specification.</p>
<p><strong>Example:</strong></p>
<pre>strptime(&quot;25/06/2016 09:50:24&quot;, &quot;%d/%m/%Y %H:%M:%S&quot;)</pre>
<p>[1] “2016-06-25 09:50:24 IST”</p>
<p>If a string does not match the format in the format string, it takes the value NA. For example, specifying dashes instead of slashes makes the parsing fail:</p>
<p><strong>Example:</strong></p>
<pre>strptime(&quot;25-06-2016 09:50:24&quot;, &quot;%d/%m/%Y %H:%M:%S&quot;)</pre>
<p>[1] NA</p>
<p>To parse milliseconds in R we use the following format string:</p>
<p><strong>Example:</strong></p>
<pre>strptime(&quot;25-06-2016 09:50:24.975&quot;, &quot;%d-%m-%Y %H:%M:%OS&quot;)</pre>
<p>[1] “2016-06-25 09:50:24.975 IST”<br>
op = options(digits.secs=3)<br>
options(op)</p>
<p>The options function allows the user to set and examine a variety of global options which affect the way in which R computes and displays its results. The argument “digits.secs” to the options function controls the maximum number of digits to print when formatting time values in seconds. Valid values are 0 to 6 with default 0.</p>
<h4></h4>
<h4>How to format dates</h4>
<p>We can format a date as per our requirement using the strftime (“string format time”) function. This function works on both POSIXct and POSIXlt date classes, and it turns a date variable into a string.</p>
<p><strong>Example:</strong></p>
<pre>now_time = Sys.time()

# Let us first check the class of the the now_time variable by calling the
# class function.

class(now_time)</pre>
<p>[1] “POSIXct” “POSIXt”</p>
<p>As can be seen, it is a “POSIXct” variable. To correctly format a date, we need to use the right naming conventions. For example, %B signifies the full name of the month, %p signifies the AM/PM time indicator, and so on. For the full list of the conventions, check the help page for the function. The required formatting conventions are placed in quotes and form the second argument of the function. An example of the strftime function usage is shown below.</p>
<pre>strftime(now_time, &quot;%I:%M%p %A, %d %B %Y&quot;)</pre>
<p>[1] “09:16AM Saturday, 29 April 2017”</p>
<h4></h4>
<h4>Extract specific parts of a date and time</h4>
<p>R has two standard date-time classes, POSIXct and POSIXlt. The POSIXct class stores dates as the number of seconds since the start of 1970, while the POSIXlt stores dates as a list, with components for seconds, minutes, hours, day of month, etc. One can use list indexing to access individual components of a POSIXlt date. These components can be viewed using the unclass function.</p>
<p><strong>Example:</strong> In this example, we use the Sys.time function, which gives the current date and time. We convert this into POSIXlt class using the as.POSIXlt function. Now we can extract the required components.</p>
<pre>time_now = as.POSIXlt(Sys.time())
print(time_now)</pre>
<p>[1] “2017-04-29 09:16:06 IST”</p>
<pre>unclass(time_now)</pre>
<p>$sec<br>
[1] 6.642435</p>
<p>$min<br>
[1] 16</p>
<p>$hour<br>
[1] 9</p>
<p>$mday<br>
[1] 29</p>
<p>$mon<br>
[1] 3</p>
<p>$year<br>
[1] 117</p>
<p>$wday<br>
[1] 6</p>
<p>$yday<br>
[1] 118</p>
<p>$isdst<br>
[1] 0</p>
<p>$zone<br>
[1] “IST”</p>
<p>$gmtoff<br>
[1] 19800</p>
<p>attr(,”tzone”)<br>
[1] “” “IST” “IST”</p>
<pre># To extract minutes
time_now$min</pre>
<p>[1] 16</p>
<pre># To extract day of the month
time_now$mday</pre>
<p>[1] 29</p>
<h3>Functions Demystified</h3>
<h4>%within% and %m+% functions</h4>
<p><strong>%within% function:</strong> This function from the lubridate package checks whether a date-time object falls in a given date-time interval. It returns a logical TRUE or FALSE as the output. The function requires a date-time interval, which is created using the interval function. We use the ymd function to convert a non-date-time object into a date-time object.</p>
<p><strong>Example:</strong></p>
<pre>library(lubridate)
dates = interval(&quot;2016-03-03&quot;, &quot;2016-06-03&quot;)
d = ymd(&quot;2016-04-21&quot;)
d %within% dates</pre>
<p>[1] TRUE</p>
<p><strong>%m+% function:</strong> This function is used to add or subtract months to/from a given date-time object.</p>
<p><strong>Examples:</strong></p>
<pre># To add a month to a date-time objects
library(lubridate)
d = ymd(&quot;2016-04-21&quot;)
d %m+% months(1)</pre>
<p>[1] “2016-05-21”</p>
<pre># To create a sequence of months from a given date-time object
library(lubridate)
d = ymd(&quot;2016-04-21&quot;)
d %m+% months(1:3)</pre>
<p>[1] “2016-05-21” “2016-06-21” “2016-07-21”</p>
<pre># To subtract a year from a given date-time object
d = ymd(&quot;2016-04-21&quot;)
d %m+% years(-1)</pre>
<p>[1] “2015-04-21”</p>
<h4>to.period function</h4>
<p>The to.period function is part of the xts package. It converts an OHLC or univariate object to a specified periodicity lower than the given data object.</p>
<p>For example, the function can convert a daily series to a monthly series, or a monthly series to a yearly one, or a one minute series to an hourly series.</p>
<p><strong>Example:</strong></p>
<pre>library(quantmod)
data = getSymbols(&quot;AAPL&quot;, src = &quot;yahoo&quot;, from = &quot;2016-01-01&quot;, to = &quot;2016-01-15&quot;,
       auto.assign = FALSE)
nrow(data)</pre>
<p>[1] 10</p>
<pre># Convert the above daily data series to weekly data.
to.period(data, period = &quot;weeks&quot;)</pre>
<p><img sizes="(max-width: 666px) 100vw, 666px" alt="" class="wp-image-8370" src="https://i1.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-weekly-VI-Pic1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>Valid period character strings include: “seconds”, “minutes”, “hours”, “days”, “weeks”, “months”, “quarters”, and “years”.</p>
<p>To convert the daily data to monthly data, the syntax will be:</p>
<p><strong>df = to.period(data,period = ‘months’)</strong></p>
<p>The result will contain the open and close for the given period, as well as the maximum and minimum over the new period, reflected in the new high and low, respectively. If volume for a period was available, the new volume will also be calculated.</p>
<h4>period.max and period.min functions</h4>
<p>The period.max and period.min functions are part of the xts package. period.max is used to calculate a maximum value per period given an arbitrary index of sections to be calculated over. The period.min function works in a similar manner to compute the minimum values.</p>
<p>The syntax is given as:</p>
<pre>period.max(x, index)
period.min(x, index)</pre>
<p>where,<br>
x – represents a univariate data object<br>
index – represents a numeric vector of endpoints</p>
<p><strong>Example:</strong></p>
<pre>library(xts)
# compute the period maximum
period.max(c(1, 1, 4, 2, 2, 6, 7, 8, -1, 20), c(0, 3, 5, 8, 10))</pre>
<p>3 5 8 10<br>
4 2 8 20</p>
<pre># compute the period minimum
period.min(c(1, 1, 4, 2, 2, 6, 7, 8, -1, 20), c(0, 3, 5, 8, 10))</pre>
<p>3 5 8 10<br>
1 2 6 -1</p>
<h3><strong>Next Step</strong></h3>
<p>We hope you liked this bulletin. In the next weekly bulletin, we will list more interesting ways and methods plus R functions for our readers.</p>
<div><a target="_blank" rel="nofollow" href="https://www.quantinsti.com/wp-content/uploads/2017/04/QuantInsti%E2%84%A2_R_Bulletin-VI-1.pdf">Download the PDF Now!</a></div>
<p>The post <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/blog/r-weekly-bulletin-vol-vi/">R Weekly Bulletin Vol – VI</a> appeared first on <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/"></a>.</p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.quantinsti.com/blog/r-weekly-bulletin-vol-vi/"> R programming</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/LRNVsvYI1l4"></a></div>