<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-v/"></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-v/"> 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-8204" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/Week-R-Bulletin_5.jpg?w=450&ssl=1" data-recalc-dims="1"></p>
<p>This week’s R bulletin will cover topics like how to avoid for-loops, add or shorten an existing vector, and play a beep sound in R. We will also cover functions like env.new function, readSeries, and the with and within functions. Hope you like this R weekly bulletin. Enjoy reading!</p>
<h3>Shortcut Keys</h3>
<p>1. To stop debugging – Shift+F8<br>
2. To quit an R session (desktop only) – Ctrl+Q<br>
3. To restart an R Session – Ctrl+Shift+0</p>
<h3>Problem Solving Ideas</h3>
<h4>Avoiding For Loop by using “with” function</h4>
<p>For Loop can be slow in terms of execution speed when we are dealing with large data sets. For faster execution, one can use the “with” function as an alternative. The syntax of the with function is given below:</p>
<p><strong>with(data, expr)</strong></p>
<p>where, “data” is typically a data frame, and “expr” stands for one or more expressions to be evaluated using the contents of the data frame. If there is more than one expression, then the expressions need to be wrapped in curly braces.</p>
<p><strong>Example:</strong> Consider the NIFTY 1-year price series. Let us find the gap opening for each day using both the methods and time them using the system.time function. Note the time taken to execute the For Loop versus the time to execute the with function in combination with the lagpad function.</p>
<pre>library(quantmod)

# Using FOR Loop
system.time({

df = read.csv(&quot;NIFTY.csv&quot;)
df = df[,c(1,3:6)]

df$GapOpen = double(nrow(df))
for ( i in 2:nrow(df)) {
    df$GapOpen[i] = round(Delt(df$CLOSE[i-1],df$OPEN[i])*100,2)
}

print(head(df))

})</pre>
<p><img sizes="(max-width: 659px) 100vw, 659px" alt="" class="wp-image-8208" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Weekly-5.png?w=450&ssl=1" data-recalc-dims="1"></p>
<pre># Using with function + lagpad, instead of FOR Loop
system.time({

dt = read.csv(&quot;NIFTY.csv&quot;)
dt = dt[,c(1,3:6)]

lagpad = function(x, k) {
c(rep(NA, k), x)[1 : length(x)]
}

dt$PrevClose = lagpad(dt$CLOSE, 1)
dt$GapOpen_ = with(dt, round(Delt(dt$PrevClose,dt$OPEN)*100,2))
print(head(dt))

})</pre>
<p><img sizes="(max-width: 667px) 100vw, 667px" alt="" class="wp-image-8210" src="https://i0.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Weekly-5-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<h4>Adding to an existing vector or shortening it</h4>
<p>Adding or shortening an existing vector can be done by assigning a new length to the vector. When we shorten a vector, the values at the end will be removed, and when we extend an existing vector, missing values will be added at the end.</p>
<p><strong>Example:</strong></p>
<pre># Shorten an existing vector
even = c(2,4,6,8,10,12)
length(even)</pre>
<p>[1] 6</p>
<pre># The new length equals the number of elements required in the vector to be shortened.
length(even) = 3
print(even)</pre>
<p>[1] 2 4 6</p>
<pre># Add to an existing vector
odd = c(1,3,5,7,9,11)
length(odd)</pre>
<p>[1] 6</p>
<pre># The new length equals the number of elements required in the extended vector.
length(odd) = 8
odd[c(7,8)] = c(13,15)
print(odd)</pre>
<p>[1] 1 3 5 7 9 11 13 15</p>
<h4>Make R beep/play a sound</h4>
<p>If you want R to play a sound/beep upon executing the code, we can do this using the “beepr” package. The beep function from the package plays a sound when the code gets executed. One also needs to install the “audio” package along with the “beepr” package.</p>
<pre>install.packages(&quot;beepr&quot;)
install.packages(&quot;audio&quot;)
library(beepr)
beep()</pre>
<p>One can select from the various sounds using the “sound” argument and by assigning one of the specified values to it.</p>
<pre>beep(sound = 9)</pre>
<p>One can keep repeating the message using beepr as illustrated in the example below (source:http: //stackoverflow.com/)</p>
<p><strong>Example:</strong></p>
<pre>work_complete &lt;- function() {
  cat(&quot;Work complete. Press esc to sound the fanfare!!!\n&quot;)
  on.exit(beepr::beep(3))

  while (TRUE) {
  beepr::beep(4)
  Sys.sleep(1)
  }
}

work_complete()</pre>
<p>One can also use the beep function to play a sound if an error occurs during the code execution.</p>
<pre>options(error = function() {beep(sound =5)})</pre>
<h3>Functions Demystified</h3>
<h4>env.new function</h4>
<p>Environments act as a storehouse. When we create variables in R from the command prompt these get stored in the R’s global environment. To access the variables stored in the global environment, one can use the following expression:</p>
<pre>head(ls(envir = globalenv()), 15)</pre>
<p>[1] “df”  “dt”  “even”  “i”  “lagpad”  “odd”</p>
<p>If we want to store the variables in a specific environment, we can assign the variable to that environment or create a new environment which will store the variable. To create a new environment we use the new.env function.</p>
<p><strong>Example:</strong></p>
<pre>my_environment = new.env()</pre>
<p>Once we create a new environment, assigning a variable to the environment can be done in multiple ways. Following are some of the methods:</p>
<pre><strong>Examples:</strong>

# By using double square brackets
my_environment[[&quot;AutoCompanies&quot;]] = c(&quot;MARUTI&quot;, &quot;TVSMOTOR&quot;, &quot;TATAMOTORS&quot;)

# By using dollar sign operator
my_environment$AutoCompanies = c(&quot;MARUTI&quot;, &quot;TVSMOTOR&quot;, &quot;TATAMOTORS&quot;)

# By using the assign function
assign(&quot;AutoCompanies&quot;, c(&quot;MARUTI&quot;, &quot;TVSMOTOR&quot;, &quot;TATAMOTORS&quot;), my_environment)</pre>
<p>The variables existing in an environment can be viewed or listed using the get function or by using the ls function.</p>
<p><strong>Example:</strong></p>
<pre>ls(envir = my_environment)</pre>
<p>[1] “AutoCompanies”</p>
<pre>get(&quot;AutoCompanies&quot;, my_environment)</pre>
<p>[1] “MARUTI”  “TVSMOTOR”  “TATAMOTORS”</p>
<h4>readSeries function</h4>
<p>The readSeries function is part of the timeSeries package, and it reads a file in table format and creates a timeSeries object from it. The main arguments of the function are:</p>
<p><strong>readSeries(file, header = TRUE, sep = “,”,format)</strong></p>
<p>where,<br>
file: the filename of a spreadsheet dataset from which to import the data records.<br>
header: a logical value indicating whether the file contains the names of the variables as its first line.<br>
format: a character string with the format in POSIX notation specifying the timestamp format.<br>
sep: the field separator used in the spreadsheet file to separate columns. By default, it is set as “;”.</p>
<p><strong>Example:</strong></p>
<pre>library(timeSeries)

# Reading the NIFTY data using read.csv
df = read.csv(file = &quot;NIFTY.csv&quot;)
print(head(df))</pre>
<p><img sizes="(max-width: 665px) 100vw, 665px" alt="" class="wp-image-8219" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Weekly-5-2.png?w=450&ssl=1" data-recalc-dims="1"></p>
<pre># Reading the NIFTY data and creating a time series object using readSeries
# function
df = readSeries(file = &quot;NIFTY.csv&quot;, header = T, sep = &quot;,&quot;, format = &quot;%Y%m%d&quot;)
print(head(df))</pre>
<p><img sizes="(max-width: 664px) 100vw, 664px" alt="" class="wp-image-8222" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Weekly-5-3.png?w=450&ssl=1" data-recalc-dims="1"></p>
<h4>with and within functions</h4>
<p>The with and within functions apply an expression to a given data set and allows one to manipulate it. The within function even keeps track of changes made, including adding or deleting elements and returns a new object with these revised contents. The syntax for these two functions is given as:</p>
<p><strong>with(data, </strong>expr<strong>)</strong><br>
<strong>within(data, </strong>expr<strong>)</strong></p>
<p>where,<br>
data – typically is a list or data frame, although other options exist for with.<br>
expr – one or more expressions to evaluate using the contents of data, the commands must be wrapped in braces if there is more than one expression to evaluate.</p>
<pre># Consider the NIFTY data
df = as.data.frame(read.csv(&quot;NIFTY.csv&quot;))
print(head(df, 3))</pre>
<p><img sizes="(max-width: 657px) 100vw, 657px" alt="" class="wp-image-8225" src="https://i1.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Weekly-5-4.png?w=450&ssl=1" data-recalc-dims="1"></p>
<pre># Example of with function:
df$Average = with(df, apply(df[3:6], 1, mean))
print(head(df, 3))</pre>
<p><img sizes="(max-width: 665px) 100vw, 665px" alt="" class="wp-image-8227" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Weekly-5-6.png?w=450&ssl=1" data-recalc-dims="1"></p>
<pre># Example of within function:
df = within(df, {
   df$Average = apply(df[3:6], 1, mean)
})
print(head(df, 3))</pre>
<p><img sizes="(max-width: 691px) 100vw, 691px" alt="" class="wp-image-8229" src="https://i0.wp.com/www.quantinsti.com/wp-content/uploads/2017/04/R-Weekly-5-7.png?w=450&ssl=1" data-recalc-dims="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-V.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-v/">R Weekly Bulletin Vol – V</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-v/"> 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/hKZGL1Gv3Ow"></a></div>