<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>R programming tutorials and exercises for data science and mathematics</title>
    <link>https://www.codertime.org/</link>
    <description>Recent content on R programming tutorials and exercises for data science and mathematics</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Sat, 06 Aug 2022 00:00:00 +0000</lastBuildDate><atom:link href="https://www.codertime.org/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Generate hours of white, pink and brown noise in R</title>
      <link>https://www.codertime.org/generate-hours-of-white-pink-brown-noise/</link>
      <pubDate>Sat, 06 Aug 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/generate-hours-of-white-pink-brown-noise/</guid>
      <description>


&lt;p&gt;&lt;a href=&#34;https://www.webmd.com/sleep-disorders/pink-noise-sleep&#34;&gt;Many studies&lt;/a&gt; suggest that white, pink and brown noise can improve focus, help with relaxation and sleep and even reduce crying in babies. Due to these potential benefits many options are available to generate color noise, including sound machines, phone apps and online clips.&lt;/p&gt;
&lt;p&gt;R also provides tools to generate white, pink and brown noise: you can create your own sound clip of a desired length and save it to a local file. A helpful package in this process is &lt;a href=&#34;https://cran.r-project.org/web/packages/tuneR/index.html&#34;&gt;tuneR&lt;/a&gt;, which offers many useful functions to process and generate sounds and write WAVE files.&lt;/p&gt;
&lt;p&gt;Let’s start by loading the &lt;code&gt;tuneR&lt;/code&gt; package and setting our default player for WAVE files (on my computer this is &lt;code&gt;aplay&lt;/code&gt;):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(tuneR)
setWavPlayer(&amp;quot;aplay&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can now easily generate multiple types of sounds via the &lt;code&gt;noise&lt;/code&gt; function. The code below constructs a Wave object that holds 4 seconds of stereo brown noise:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;brown_noise &amp;lt;- noise(kind = &amp;quot;red&amp;quot;, duration = 4, xunit = &amp;quot;time&amp;quot;, stereo = TRUE)
# kind = &amp;quot;red&amp;quot;: brown noise
# kind = &amp;quot;white&amp;quot;: white noise
# kind = &amp;quot;pink&amp;quot;: pink noise&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can plot the two channels of this Wave object (both channels are generated independently):&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot(brown_noise)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/generate-hours-of-white-pink-brown-noise/index_files/figure-html/unnamed-chunk-4-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;p&gt;And finally we can play the sound clip directly from R or save it to a local file:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;play(brown_noise)
writeWave(brown_noise, filename = &amp;quot;brown_noise_sample.wav&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;pre-recorded-loops-of-white-pink-and-brown-noise&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Pre-recorded loops of white, pink and brown noise&lt;/h2&gt;
&lt;p&gt;As a bonus I am including a pre-recorded loop for each noise type that you can listen to below and compare (&lt;span style=&#34;color:DarkSlateBlue&#34;&gt;&lt;em&gt;if you are reading this post via RSS feed then visit my &lt;a href=&#34;https://www.codertime.org/generate-hours-of-white-pink-brown-noise/&#34;&gt;original page&lt;/a&gt; to access the audio&lt;/em&gt;&lt;/span&gt;).&lt;/p&gt;
&lt;table&gt;
&lt;tr&gt;
&lt;td style=&#34;vertical-align: top;&#34;&gt;
&lt;strong&gt;White noise loop:&lt;/strong&gt;
&lt;/td&gt;
&lt;td&gt;
&lt;audio controls preload=&#34;metadata&#34; loop&gt;
&lt;source src=&#34;white_noise_hour.wav&#34; type=&#34;audio/wav&#34;&gt;
&lt;/audio&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34;vertical-align: top;&#34;&gt;
&lt;strong&gt;Pink noise loop:&lt;/strong&gt;
&lt;/td&gt;
&lt;td&gt;
&lt;audio controls preload=&#34;metadata&#34; loop&gt;
&lt;source src=&#34;pink_noise_hour.wav&#34; type=&#34;audio/wav&#34;&gt;
&lt;/audio&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&#34;vertical-align: top;&#34;&gt;
&lt;strong&gt;Brown noise loop:&lt;/strong&gt;
&lt;/td&gt;
&lt;td&gt;
&lt;audio controls preload=&#34;metadata&#34; loop&gt;
&lt;source src=&#34;brown_noise_hour.wav&#34; type=&#34;audio/wav&#34;&gt;
&lt;/audio&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>How to write insertion sort in R</title>
      <link>https://www.codertime.org/how-to-program-insertion-sort-in-r/</link>
      <pubDate>Thu, 04 Aug 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/how-to-program-insertion-sort-in-r/</guid>
      <description>


&lt;div id=&#34;getting-started-with-insertion-sort&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;Getting started with insertion sort&lt;/h2&gt;
&lt;p&gt;The insertion sort algorithm works by constructing a sorted vector one element at a time:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;First element&lt;/strong&gt;: a vector with one element is already trivially sorted.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Second element&lt;/strong&gt;: if the second element is less than the first, swap them. We now have an increasing sorted vector of length two.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Third element&lt;/strong&gt;: perform any necessary swaps to move the third element into the correct position relative to the first to elements. We now have an increasing sorted vector of length three.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This process continues until the entire input vector is fully sorted.&lt;/p&gt;
&lt;p&gt;For example, we want to sort the vector 4, 3, 2, 1 in increasing order using insertion sort. The algorithm will perform the following rearrangements of our input:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Input&lt;/strong&gt;: 4, 3, 2, 1&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Intermediary step&lt;/strong&gt;: 3, 4, 2, 1 (first two elements sorted in increasing order)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Intermediary step&lt;/strong&gt;: 2, 3, 4, 1 (first three elements sorted in increasing order)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Final step&lt;/strong&gt;: 1, 2, 3, 4 (all four elements sorted in increasing order)&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;the-insertion-sort-implementation-in-r&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;The insertion sort implementation in R&lt;/h2&gt;
&lt;p&gt;Let’s write an insertion sort function in R that arranges a numeric vector of two or more elements in increasing order:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;insertion_sort &amp;lt;- function(x) {
  # The first loop goes through the elements of x to build a partially sorted vector
  # The first element is already trivially sorted, so we start the index at 2
  for (i in 2:length(x)) {
    # The second loop performs swaps to place the current element in its correct place
    for (j in i:2) {
      if (x[j - 1] &amp;gt; x[j]) {
        tmp &amp;lt;- x[j]
        x[j] &amp;lt;- x[j - 1]
        x[j - 1] &amp;lt;- tmp
      }
    }
  }
  # The sorted vector is returned
  return(x)
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;testing-our-insertion-sort-r-program&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;Testing our insertion sort R program&lt;/h2&gt;
&lt;p&gt;We can now test our insertion sort function on a few random input vectors:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;for (i in 1:4) {
  x &amp;lt;- sample(1:10)
  cat(&amp;quot;Input: &amp;quot;, x, &amp;quot;\n&amp;quot;)
  cat(&amp;quot;Output: &amp;quot;, insertion_sort(x), &amp;quot;\n&amp;quot;)
}&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Input:  10 1 3 4 5 2 6 9 7 8 
## Output:  1 2 3 4 5 6 7 8 9 10 
## Input:  6 10 2 7 8 3 4 9 5 1 
## Output:  1 2 3 4 5 6 7 8 9 10 
## Input:  4 3 10 1 9 7 2 6 5 8 
## Output:  1 2 3 4 5 6 7 8 9 10 
## Input:  10 8 3 9 2 5 6 4 1 7 
## Output:  1 2 3 4 5 6 7 8 9 10&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;All output vectors are sorted in increasing order as expected.&lt;/p&gt;
&lt;p&gt;We can also add two lines to our program that print the current state of the vector after each step:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;insertion_sort &amp;lt;- function(x) {
  # The first loop goes through the elements of x to build a partially sorted vector
  # The first element is already trivially sorted, so we start the index at 2
  for (i in 2:length(x)) {
    # The second loop performs swaps to place the current element in its correct place
    for (j in i:2) {
      if (x[j - 1] &amp;gt; x[j]) {
        tmp &amp;lt;- x[j]
        x[j] &amp;lt;- x[j - 1]
        x[j - 1] &amp;lt;- tmp
      }
      cat(&amp;quot;Swap performed:&amp;quot;, x, &amp;quot;\n&amp;quot;)
    }
    cat(&amp;quot;First&amp;quot;, i, &amp;quot;elements are sorted: &amp;quot;, x, &amp;quot;\n&amp;quot;)
  }
  # The sorted vector is returned
  return(x)
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This allows us to track the progress of insertion sort as it orders the input vector:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;insertion_sort(c(4, 3, 2, 1))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Swap performed: 3 4 2 1 
## First 2 elements are sorted:  3 4 2 1 
## Swap performed: 3 2 4 1 
## Swap performed: 2 3 4 1 
## First 3 elements are sorted:  2 3 4 1 
## Swap performed: 2 3 1 4 
## Swap performed: 2 1 3 4 
## Swap performed: 1 2 3 4 
## First 4 elements are sorted:  1 2 3 4&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1 2 3 4&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Spirals and trigonometric functions: R exercise #9</title>
      <link>https://www.codertime.org/r-programming-exercise-spirals-trigonometric-functions/</link>
      <pubDate>Wed, 03 Aug 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-programming-exercise-spirals-trigonometric-functions/</guid>
      <description>


&lt;p&gt;Define a &lt;strong&gt;one-line&lt;/strong&gt; R function &lt;code&gt;FUN&lt;/code&gt; that provides the following output:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(seq(from = 0, to = 20, by = 0.1))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/r-programming-exercise-spirals-trigonometric-functions/index_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;480&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(seq(from = 0, to = 100, by = 0.1))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/r-programming-exercise-spirals-trigonometric-functions/index_files/figure-html/unnamed-chunk-3-2.png&#34; width=&#34;480&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(seq(from = 0, to = 200, by = 0.1))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/r-programming-exercise-spirals-trigonometric-functions/index_files/figure-html/unnamed-chunk-3-3.png&#34; width=&#34;480&#34; /&gt;&lt;/p&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;We can write the function as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) plot(cbind(x * sin(x), x * cos(x)), type = &amp;quot;l&amp;quot;, panel.first = grid(), ann = FALSE, col = &amp;quot;red&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This definition uses the functions &lt;code&gt;cos&lt;/code&gt; and &lt;code&gt;sin&lt;/code&gt; to plot a spiral with the origin at 0 and also adds grid lines consistent with the axis ticks:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(seq(from = 0, to = 20, by = 0.1))&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&#34;https://www.codertime.org/r-programming-exercise-spirals-trigonometric-functions/index_files/figure-html/unnamed-chunk-5-1.png&#34; width=&#34;480&#34; /&gt;
&lt;/details&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Access and map the latest monkeypox case data in R</title>
      <link>https://www.codertime.org/plot-monkeypox-case-map-r-choropleth/</link>
      <pubDate>Sun, 31 Jul 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/plot-monkeypox-case-map-r-choropleth/</guid>
      <description>


&lt;p&gt;The ongoing monkeypox outbreak in many countries outside of the endemic regions in Africa has drawn significant attention over the past months. &lt;strong&gt;Government agencies as well as academic and industry teams have released open-access databases to track case numbers over time across different countries and visualizations have been made available to help identify and interpret trends.&lt;/strong&gt; This sharing of real-time data can help support response efforts by offering insight into the dynamics of this outbreak.&lt;/p&gt;
&lt;p&gt;I will talk about some of the currently available monkeypox case databases, with a focus on high-quality resources that are frequently updated and easily imported and processed in R. I will show a few examples of how this information can be mapped and visualized. &lt;strong&gt;Overall this article aims to help you get started with your own exploration of the available raw data&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;We will use a few R packages to construct choropleth maps:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;library(ggplot2)
library(dplyr)
library(maps)
library(viridis)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At the time of writing this article, one of the most comprehensive monkeypox case databases is accessible via the &lt;a href=&#34;https://github.com/globaldothealth/monkeypox&#34;&gt;Global.health Monkeypox repository&lt;/a&gt;. This resource is updated in near real-time by a team of curators that aggregate data from verified sources including governments, public health organisations and health official statements. You can find more details on their methodology &lt;a href=&#34;https://www.thelancet.com/journals/laninf/article/PIIS1473-3099(22)00359-0/fulltext&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;We can load the latest worldwide case data into R directly from the Global.health GitHub repository:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Read worldwide case data
case_series &amp;lt;- read.csv(&amp;quot;https://raw.githubusercontent.com/globaldothealth/monkeypox/main/timeseries-country-confirmed.csv&amp;quot;)
head(case_series)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##         Date Cases Cumulative_cases   Country
## 1 2022-07-25     1                1   Andorra
## 2 2022-07-26     2                3   Andorra
## 3 2022-07-27     0                3   Andorra
## 4 2022-07-28     0                3   Andorra
## 5 2022-07-29     0                3   Andorra
## 6 2022-05-27     2                2 Argentina&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each row records the number of cases and cumulative cases for a country at a given date. We also extract data from the &lt;code&gt;maps&lt;/code&gt; package for plotting with ggplot2:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;world_map &amp;lt;- map_data(&amp;quot;world&amp;quot;)
head(world_map)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##        long      lat group order region subregion
## 1 -69.89912 12.45200     1     1  Aruba      &amp;lt;NA&amp;gt;
## 2 -69.89571 12.42300     1     2  Aruba      &amp;lt;NA&amp;gt;
## 3 -69.94219 12.43853     1     3  Aruba      &amp;lt;NA&amp;gt;
## 4 -70.00415 12.50049     1     4  Aruba      &amp;lt;NA&amp;gt;
## 5 -70.06612 12.54697     1     5  Aruba      &amp;lt;NA&amp;gt;
## 6 -70.05088 12.59707     1     6  Aruba      &amp;lt;NA&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This table includes latitude and longitude values for the countries that will be represented in our plots. All the information needed to draw geographic maps of case numbers is now ready. Let’s define a function with the following characteristics:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Inputs&lt;/strong&gt;: date, latitude range, longitude range&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Output&lt;/strong&gt;: map of cumulative case counts on the date provided, bounded by the requested latitude and longitude values&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot_case_map &amp;lt;- function(date, xlim, ylim) {
  # Pre-process case and map data
  case_map &amp;lt;- case_series[which(case_series$Date == date), c(4, 3)]
  colnames(case_map)[1] &amp;lt;- &amp;quot;region&amp;quot;
  case_map$region[which(case_map$region == &amp;quot;United States&amp;quot;)] &amp;lt;- &amp;quot;USA&amp;quot;
  case_map$region[which(case_map$region == &amp;quot;United Kingdom&amp;quot;)] &amp;lt;- &amp;quot;UK&amp;quot;
  case_map$region[which(case_map$region == &amp;quot;Democratic Republic Of The Congo&amp;quot;)] &amp;lt;- &amp;quot;Democratic Republic of the Congo&amp;quot;
  case_map$region[which(case_map$region == &amp;quot;Bosnia And Herzegovina&amp;quot;)] &amp;lt;- &amp;quot;Bosnia and Herzegovina&amp;quot;
  if (&amp;quot;Gibraltar&amp;quot; %in% case_map$region) {
    case_map &amp;lt;- case_map[-which(case_map$region == &amp;quot;Gibraltar&amp;quot;), ]
  }
  if (length(setdiff(world_map$region, case_map$region)) &amp;gt; 0) {
    case_map_other &amp;lt;- as.data.frame(cbind(setdiff(world_map$region, case_map$region), NA))
    colnames(case_map_other) &amp;lt;- c(&amp;quot;region&amp;quot;, &amp;quot;Cumulative_cases&amp;quot;)
    case_map &amp;lt;- rbind(case_map, case_map_other)
  }
  case_map$Cumulative_cases &amp;lt;- as.numeric(case_map$Cumulative_cases)
  case_map &amp;lt;- left_join(case_map, world_map, by = &amp;quot;region&amp;quot;)

  # Plot case map
  ggplot(case_map, aes(long, lat, group = group)) +
    geom_polygon(aes(fill = Cumulative_cases), color = &amp;quot;white&amp;quot;, size = 0.2) +
    scale_fill_viridis_c() +
    theme_linedraw() +
    theme(legend.position = &amp;quot;right&amp;quot;) +
    labs(fill = &amp;quot;Cumulative cases&amp;quot;) +
    theme(legend.direction = &amp;quot;vertical&amp;quot;) +
    coord_map(xlim = xlim, ylim = ylim)
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can now plot choropleth maps representing cumulative monkeypox case numbers for given dates and geographic regions:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Plot world case map as of July 29th 2022:
plot_case_map(&amp;quot;2022-07-29&amp;quot;, c(-180, 180), c(-55, 90))&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&#34;figure&#34;&gt;&lt;span style=&#34;display:block;&#34; id=&#34;fig:unnamed-chunk-6&#34;&gt;&lt;/span&gt;
&lt;img src=&#34;https://www.codertime.org/plot-monkeypox-case-map-r-choropleth/index_files/figure-html/unnamed-chunk-6-1.png&#34; alt=&#34;World case map on July 29th 2022&#34; width=&#34;768&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;
Figure 1: World case map on July 29th 2022
&lt;/p&gt;
&lt;/div&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Plot world case map as of May 29th 2022:
plot_case_map(&amp;quot;2022-05-29&amp;quot;, c(-180, 180), c(-55, 90))&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&#34;figure&#34;&gt;&lt;span style=&#34;display:block;&#34; id=&#34;fig:unnamed-chunk-7&#34;&gt;&lt;/span&gt;
&lt;img src=&#34;https://www.codertime.org/plot-monkeypox-case-map-r-choropleth/index_files/figure-html/unnamed-chunk-7-1.png&#34; alt=&#34;World case map on May 29th 2022&#34; width=&#34;768&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;
Figure 2: World case map on May 29th 2022
&lt;/p&gt;
&lt;/div&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Plot Europe case map as of July 29th 2022:
plot_case_map(&amp;quot;2022-07-29&amp;quot;, c(-22, 38), c(35, 64))&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&#34;figure&#34;&gt;&lt;span style=&#34;display:block;&#34; id=&#34;fig:unnamed-chunk-8&#34;&gt;&lt;/span&gt;
&lt;img src=&#34;https://www.codertime.org/plot-monkeypox-case-map-r-choropleth/index_files/figure-html/unnamed-chunk-8-1.png&#34; alt=&#34;Europe case map on July 29th 2022&#34; width=&#34;768&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;
Figure 3: Europe case map on July 29th 2022
&lt;/p&gt;
&lt;/div&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Plot Europe case map as of May 29th 2022:
plot_case_map(&amp;quot;2022-05-29&amp;quot;, c(-22, 38), c(35, 64))&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&#34;figure&#34;&gt;&lt;span style=&#34;display:block;&#34; id=&#34;fig:unnamed-chunk-9&#34;&gt;&lt;/span&gt;
&lt;img src=&#34;https://www.codertime.org/plot-monkeypox-case-map-r-choropleth/index_files/figure-html/unnamed-chunk-9-1.png&#34; alt=&#34;Europe case map on May 29th 2022&#34; width=&#34;768&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;
Figure 4: Europe case map on May 29th 2022
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;A similar map of the latest cumulative monkeypox case numbers in the US can be plotted based on information published and updated regularly by the &lt;a href=&#34;https://www.cdc.gov/poxvirus/monkeypox/response/2022/us-map.html&#34;&gt;CDC&lt;/a&gt;. The data can be accessed via the “Download Data (CSV)” button at the bottom of the page.&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Download US case data
us_case_map &amp;lt;- read.table(&amp;quot;~/Downloads/Monkeypox and Orthopoxvirus Cases in the U.S..csv&amp;quot;, header = T, sep = &amp;quot;,&amp;quot;)
head(us_case_map)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##        State Cases  Range
## 1    Alabama    16 1 to 2
## 2     Alaska     1 1 to 2
## 3    Arizona    50 1 to 2
## 4   Arkansas     4 1 to 2
## 5 California   799 1 to 2
## 6   Colorado    53 1 to 2&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This file contains the latest case numbers for each US state. We can now generate a choropleth map based on this CDC data:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Pre-process US case and map data
us_map &amp;lt;- map_data(&amp;quot;state&amp;quot;)
us_case_map &amp;lt;- us_case_map[-which(us_case_map$State %in% c(&amp;quot;Alaska&amp;quot;, &amp;quot;Hawaii&amp;quot;, &amp;quot;Puerto Rico&amp;quot;, &amp;quot;Non-US Resident&amp;quot;)), -3]
colnames(us_case_map)[1] &amp;lt;- &amp;quot;region&amp;quot;
us_case_map$region &amp;lt;- tolower(us_case_map$region)
if (length(setdiff(us_map$region, us_case_map$region)) &amp;gt; 0) {
  us_case_map_other &amp;lt;- as.data.frame(cbind(setdiff(us_map$region, us_case_map$region), NA))
  colnames(us_case_map_other) &amp;lt;- c(&amp;quot;region&amp;quot;, &amp;quot;Cases&amp;quot;)
  us_case_map &amp;lt;- rbind(us_case_map, us_case_map_other)
}
us_case_map$Cases &amp;lt;- as.numeric(us_case_map$Cases)
us_case_map &amp;lt;- left_join(us_case_map, us_map, by = &amp;quot;region&amp;quot;)

# Plot US case map
ggplot(us_case_map, aes(long, lat, group = group)) +
  geom_polygon(aes(fill = Cases), color = &amp;quot;white&amp;quot;, size = 0.2) +
  scale_fill_viridis_c() +
  theme_linedraw() +
  theme(legend.position = &amp;quot;right&amp;quot;) +
  labs(fill = &amp;quot;Total cases&amp;quot;) +
  theme(legend.direction = &amp;quot;vertical&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&#34;figure&#34;&gt;&lt;span style=&#34;display:block;&#34; id=&#34;fig:unnamed-chunk-11&#34;&gt;&lt;/span&gt;
&lt;img src=&#34;https://www.codertime.org/plot-monkeypox-case-map-r-choropleth/index_files/figure-html/unnamed-chunk-11-1.png&#34; alt=&#34;US case map on July 29th 2022&#34; width=&#34;768&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;
Figure 5: US case map on July 29th 2022
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;We can also graph case trends over time for individual countries based on the published Global.health Monkeypox repository data. Let’s define a function that takes a country name as input and plots:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;dates on the x-axis&lt;/li&gt;
&lt;li&gt;cumulative case counts on the left y-axis in red&lt;/li&gt;
&lt;li&gt;daily case counts on the right y-axis in blue&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot_case_series &amp;lt;- function(country) {
  # Plot cumulative case counts in red
  country_series &amp;lt;- case_series[which(case_series$Country == country), ]
  par(oma = c(1, 1, 1, 3))
  plot(country_series$Cumulative_cases, type = &amp;quot;l&amp;quot;, xaxt = &amp;quot;n&amp;quot;, xlab = NA, main = paste(country, &amp;quot;reported case time series&amp;quot;), ylab = &amp;quot;Cumulative cases&amp;quot;, col.lab = &amp;quot;red&amp;quot;, col = &amp;quot;red&amp;quot;)
  axis(1, at = 1:nrow(country_series), labels = country_series$Date, las = 2, gap.axis = 1, cex.axis = 0.8)

  # Plot daily case counts in blue
  par(new = TRUE)
  plot(country_series$Cases, type = &amp;quot;l&amp;quot;, axes = FALSE, xlab = NA, ylab = NA, col = &amp;quot;blue&amp;quot;)
  axis(4, at = pretty(range(country_series$Cases)))
  mtext(&amp;quot;Cases&amp;quot;, side = 4, line = 3, col = &amp;quot;blue&amp;quot;)
  grid()
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can now use this function to explore case trends for multiple countries:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot_case_series(&amp;quot;Canada&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/plot-monkeypox-case-map-r-choropleth/index_files/figure-html/unnamed-chunk-13-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot_case_series(&amp;quot;United States&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/plot-monkeypox-case-map-r-choropleth/index_files/figure-html/unnamed-chunk-13-2.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;plot_case_series(&amp;quot;United Kingdom&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/plot-monkeypox-case-map-r-choropleth/index_files/figure-html/unnamed-chunk-13-3.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;This was a short overview of a few high-quality public databases that aggregate and curate monkeypox case numbers, and we explored some of the options offered by R for custom analyses and visualizations of this raw data.&lt;/strong&gt;&lt;/p&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Programming a simple minimax chess engine in R</title>
      <link>https://www.codertime.org/minimax-chess-engine-programming-r/</link>
      <pubDate>Sat, 23 Jul 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/minimax-chess-engine-programming-r/</guid>
      <description>
&lt;script src=&#34;https://www.codertime.org/minimax-chess-engine-programming-r/index_files/htmlwidgets/htmlwidgets.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://www.codertime.org/minimax-chess-engine-programming-r/index_files/jquery/jquery.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://www.codertime.org/minimax-chess-engine-programming-r/index_files/chessjs/chess.min.js&#34;&gt;&lt;/script&gt;
&lt;link href=&#34;https://www.codertime.org/minimax-chess-engine-programming-r/index_files/chessboardjs/chessboard-0.3.0.min.css&#34; rel=&#34;stylesheet&#34; /&gt;
&lt;script src=&#34;https://www.codertime.org/minimax-chess-engine-programming-r/index_files/chessboardjs/chessboard-0.3.0.min.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://www.codertime.org/minimax-chess-engine-programming-r/index_files/chessboardjs.themes/chessboardjs.themes.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://www.codertime.org/minimax-chess-engine-programming-r/index_files/chessboardjs.themes/chessboardjs.themes.data.js&#34;&gt;&lt;/script&gt;
&lt;script src=&#34;https://www.codertime.org/minimax-chess-engine-programming-r/index_files/chessboardjs-binding/chessboardjs.js&#34;&gt;&lt;/script&gt;


&lt;div id=&#34;why-write-a-chess-engine-in-r&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;Why write a chess engine in R?&lt;/h2&gt;
&lt;p&gt;Chess has always fascinated me. This is a game with simple rules that takes a lot of practice to master. No information is hidden from the players: the game state is clearly visible on the board, but strategies can be complex and subtle. This combination of simple rules and complex strategy becomes very relevant when attempting to write a chess engine. As we will see, a single line of R code is sufficient to implement a program that returns random legal moves. Creating a chess engine that actually plays well is another story.&lt;/p&gt;
&lt;p&gt;Powerful chess engines have been developed that can currently defeat most human players. These are highly optimized pieces of software that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;search through the space of available moves very quickly to query positions many moves ahead&lt;/li&gt;
&lt;li&gt;often use expert knowledge of the game or pre-computed results to evaluate positions accurately (examples include opening books, endgame databases and evaluation heuristics)&lt;/li&gt;
&lt;li&gt;rely on vast amounts of computer resources for training and leverage advanced machine learning models such as neural networks for position evaluation&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;My goal is not to recreate any of these advanced efforts. This would be unrealistic and, as a casual chess player and avid R programmer, I am more interested to discover the opportunities that R offers around chess. For example, multiple packages are available to plot game positions or to generate lists of legal moves. I am also curious to explore some of the standard algorithms used in chess engines (starting with minimax) and see how simple R implementations of these approaches translate into enjoyable chess games.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;In essence, my simple R chess engine should be fun and informative to write and also entertaining to play against as a casual player. It serves as an opportunity to explore an uncommon but fun application of R.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;With this introduction let’s dive into the world of R chess!&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;getting-started-basic-chess-functions-in-r-and-first-chess-engine&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;Getting started: basic chess functions in R and first ‘chess engine’&lt;/h2&gt;
&lt;p&gt;Before we start implementing any game logic it is important to ensure that some basic chess functionality is available. This includes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;plotting the game board&lt;/li&gt;
&lt;li&gt;listing all legal moves for a given position&lt;/li&gt;
&lt;li&gt;recognizing when a game is won or drawn&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;a href=&#34;https://cran.r-project.org/web/packages/rchess/index.html&#34;&gt;rchess package&lt;/a&gt; provides excellent functions that address these points.&lt;/p&gt;
&lt;p&gt;Let’s start a new chess game and plot the board:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Load the rchess package:
library(rchess)
# Create a new game:
chess_game &amp;lt;- Chess$new()
# Plot the current position:
plot(chess_game)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;htmlwidget-1&#34; style=&#34;width:300px;height:300px;&#34; class=&#34;chessboardjs html-widget&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-1&#34;&gt;{&#34;x&#34;:{&#34;fen&#34;:&#34;rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1&#34;},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;What moves are available for white? We can get a list of all legal moves via the &lt;code&gt;moves&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chess_game$moves()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1] &amp;quot;a3&amp;quot;  &amp;quot;a4&amp;quot;  &amp;quot;b3&amp;quot;  &amp;quot;b4&amp;quot;  &amp;quot;c3&amp;quot;  &amp;quot;c4&amp;quot;  &amp;quot;d3&amp;quot;  &amp;quot;d4&amp;quot; 
##  [9] &amp;quot;e3&amp;quot;  &amp;quot;e4&amp;quot;  &amp;quot;f3&amp;quot;  &amp;quot;f4&amp;quot;  &amp;quot;g3&amp;quot;  &amp;quot;g4&amp;quot;  &amp;quot;h3&amp;quot;  &amp;quot;h4&amp;quot; 
## [17] &amp;quot;Na3&amp;quot; &amp;quot;Nc3&amp;quot; &amp;quot;Nf3&amp;quot; &amp;quot;Nh3&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can pick a move and update the game accordingly:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chess_game$move(&amp;quot;e4&amp;quot;)
plot(chess_game)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;htmlwidget-2&#34; style=&#34;width:300px;height:300px;&#34; class=&#34;chessboardjs html-widget&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-2&#34;&gt;{&#34;x&#34;:{&#34;fen&#34;:&#34;rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1&#34;},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;The next player to move is black:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chess_game$turn()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;b&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and the available moves are:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chess_game$moves()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1] &amp;quot;Nc6&amp;quot; &amp;quot;Na6&amp;quot; &amp;quot;Nh6&amp;quot; &amp;quot;Nf6&amp;quot; &amp;quot;a6&amp;quot;  &amp;quot;a5&amp;quot;  &amp;quot;b6&amp;quot;  &amp;quot;b5&amp;quot; 
##  [9] &amp;quot;c6&amp;quot;  &amp;quot;c5&amp;quot;  &amp;quot;d6&amp;quot;  &amp;quot;d5&amp;quot;  &amp;quot;e6&amp;quot;  &amp;quot;e5&amp;quot;  &amp;quot;f6&amp;quot;  &amp;quot;f5&amp;quot; 
## [17] &amp;quot;g6&amp;quot;  &amp;quot;g5&amp;quot;  &amp;quot;h6&amp;quot;  &amp;quot;h5&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using the &lt;code&gt;moves&lt;/code&gt; function we can already write a first chess engine that returns a random legal move:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Random move generator for a given position:
get_random_move &amp;lt;- function(chess_game) {
  return(sample(chess_game$moves(), size = 1))
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can use this simple function to generate full chess games with both sides played by the computer:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Set up a new game
chess_game &amp;lt;- Chess$new()

# Perform random legal moves until the game ends in mate or draw
while (!chess_game$game_over()) {
  chess_game$move(get_random_move(chess_game))
}

# Plot the final position
plot(chess_game)&lt;/code&gt;&lt;/pre&gt;
&lt;div id=&#34;htmlwidget-3&#34; style=&#34;width:300px;height:300px;&#34; class=&#34;chessboardjs html-widget&#34;&gt;&lt;/div&gt;
&lt;script type=&#34;application/json&#34; data-for=&#34;htmlwidget-3&#34;&gt;{&#34;x&#34;:{&#34;fen&#34;:&#34;7N/r1nb4/4kQ2/1p1pP1p1/p1p3p1/1P5P/P1P3P1/R2K1B1R b - - 0 43&#34;},&#34;evals&#34;:[],&#34;jsHooks&#34;:[]}&lt;/script&gt;
&lt;p&gt;This game ended in a win for white and took only a few seconds to run. We can also get a summary of the board in &lt;a href=&#34;https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation&#34;&gt;FEN notation&lt;/a&gt; by using the &lt;code&gt;fen&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chess_game$fen()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;7N/r1nb4/4kQ2/1p1pP1p1/p1p3p1/1P5P/P1P3P1/R2K1B1R b - - 0 43&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This FEN representation of the game state allows us to easily determine which pieces are still available for each player.&lt;/p&gt;
&lt;p&gt;We can also confirm that the game is over, that checkmate occurred and that black is in check:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chess_game$game_over()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chess_game$in_checkmate()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;chess_game$in_check()&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;improving-our-chess-logic-heuristic-position-evaluation-function&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Improving our chess logic: heuristic position evaluation function&lt;/h2&gt;
&lt;p&gt;While playing a full random game is surprisingly simple with the help of the &lt;code&gt;rchess&lt;/code&gt; package, we would like to start improving our engine in two ways:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Evaluation function&lt;/strong&gt;: implement a simple heuristic to evaluate individual positions based on the pieces on the board and the safety of the king&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Search function&lt;/strong&gt;: implement an algorithm that allows our engine to search through positions multiple moves ahead&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let’s first work on the position evaluation function, which is usually performed from the perspective of white. More precisely, scores greater than zero indicate an advantage for white and scores less than zero point to an advantage for black. Our scores are based on three aspects of the position being evaluated:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Is this position a win for one of the players or a draw? If white won the score is 1000. If black won the score is -1000. In case of a draw the score in 0.&lt;/li&gt;
&lt;li&gt;What is the material advantage for white? Each piece receives a value (9 points for queens, 5 points for rooks, 3 points for bishops and knights and 1 point for pawns) and the total piece value for black is subtracted from the total piece value for white.&lt;/li&gt;
&lt;li&gt;If the white king is in check subtract one point from the position score. If the black king is in check add one point to the position score.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is a fairly standard (although highly simplified) way to define an evaluation function: white will choose moves with high scores and black will prefer moves with low scores. Both players can thus use the same position evaluation function, which simplifies our program.&lt;/p&gt;
&lt;p&gt;Let’s implement these simple heuristics in R:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Position evaluation function
evaluate_position &amp;lt;- function(position) {
  # Test if black won
  if (position$in_checkmate() &amp;amp; (position$turn() == &amp;quot;w&amp;quot;)) {
    return(-1000)
  }
  # Test if white won
  if (position$in_checkmate() &amp;amp; (position$turn() == &amp;quot;b&amp;quot;)) {
    return(1000)
  }
  # Test if game ended in a draw
  if (position$game_over()) {
    return(0)
  }

  # Compute material advantage
  position_fen &amp;lt;- strsplit(strsplit(position$fen(), split = &amp;quot; &amp;quot;)[[1]][1], split = &amp;quot;&amp;quot;)[[1]]
  white_score &amp;lt;- length(which(position_fen == &amp;quot;Q&amp;quot;)) * 9 + length(which(position_fen == &amp;quot;R&amp;quot;)) * 5 + length(which(position_fen == &amp;quot;B&amp;quot;)) * 3 + length(which(position_fen == &amp;quot;N&amp;quot;)) * 3 + length(which(position_fen == &amp;quot;P&amp;quot;))
  black_score &amp;lt;- length(which(position_fen == &amp;quot;q&amp;quot;)) * 9 + length(which(position_fen == &amp;quot;r&amp;quot;)) * 5 + length(which(position_fen == &amp;quot;b&amp;quot;)) * 3 + length(which(position_fen == &amp;quot;n&amp;quot;)) * 3 + length(which(position_fen == &amp;quot;p&amp;quot;))

  # Evaluate king safety
  check_score &amp;lt;- 0
  if (position$in_check() &amp;amp; (position$turn() == &amp;quot;w&amp;quot;)) check_score &amp;lt;- -1
  if (position$in_check() &amp;amp; (position$turn() == &amp;quot;b&amp;quot;)) check_score &amp;lt;- 1

  # Return final position score
  return(white_score - black_score + check_score)
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Applying this function to our previous game we see that it correctly recognizes a win by white by returning a score of 1000:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;evaluate_position(chess_game)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1000&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;improving-our-chess-logic-minimax-search&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Improving our chess logic: minimax search&lt;/h2&gt;
&lt;p&gt;So far we have implemented a function that quantifies whether a given position is advantageous for white or black. The second part of our engine builds on this result and focuses on searching through potential next moves to identify the best choice. We will use an algorithm called minimax to perform this search.&lt;/p&gt;
&lt;p&gt;The figure below shows how minimax works on a toy example:&lt;/p&gt;
&lt;div class=&#34;figure&#34;&gt;&lt;span style=&#34;display:block;&#34; id=&#34;fig:unnamed-chunk-14&#34;&gt;&lt;/span&gt;
&lt;img src=&#34;chess_minimax.png&#34; alt=&#34;Example of minimax search for the best next move (white to move in the current position)&#34; width=&#34;100%&#34; /&gt;
&lt;p class=&#34;caption&#34;&gt;
Figure 1: Example of minimax search for the best next move (white to move in the current position)
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;White starts at the root position and has two move options. For each option, black has two replies available. Figure 1 summarizes this tree of move possibilities and shows the heuristic score for each of the leaf nodes based on the position evaluation function we just defined.&lt;/p&gt;
&lt;p&gt;Black will always pick the move that minimizes the heuristic score. In the right branch black will play the move that results in a score of -3, so white can predict that picking the right branch move will lead to a position with score -3. Picking the left branch move however will result in a score of 0, since black cannot capture any material. Based on this reasoning, white will chose the left branch since it leads to a more advantageous outcome even after black plays its best reply.&lt;/p&gt;
&lt;p&gt;This minimax strategy is powerful in chess since it looks multiple moves ahead and evaluates positions assuming that each player makes optimal choices. We can also increase the height of this tree: the position evaluation will be more precise since more moves are tested but the runtime will also increase.&lt;/p&gt;
&lt;p&gt;Let’s implement this algorithm in R:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Score position via minimax strategy
minimax_scoring &amp;lt;- function(chess_game, depth) {
  # If the game is already over or the depth limit is reached
  # then return the heuristic evaluation of the position
  if (depth == 0 | chess_game$game_over()) {
    return(evaluate_position(chess_game))
  }

  # Run the minimax scoring recursively on every legal next move, making sure the search depth is not exceeded
  next_moves &amp;lt;- chess_game$moves()
  next_move_scores &amp;lt;- vector(length = length(next_moves))
  for (i in 1:length(next_moves)) {
    chess_game$move(next_moves[i])
    next_move_scores[i] &amp;lt;- minimax_scoring(chess_game, depth - 1)
    chess_game$undo()
  }

  # White will select the move that maximizes the position score
  # Black will select the move that minimizes the position score
  if (chess_game$turn() == &amp;quot;w&amp;quot;) {
    return(max(next_move_scores))
  } else {
    return(min(next_move_scores))
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This completes the &lt;code&gt;minimax_scoring&lt;/code&gt; function that returns a score given an input position. Now we just need a wrapper function to evaluate all legal next moves via &lt;code&gt;minimax_scoring&lt;/code&gt; and return the optimal choice:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Select the next move based on the minimax scoring
get_minimax_move &amp;lt;- function(chess_game) {
  # Score all next moves via minimax
  next_moves &amp;lt;- chess_game$moves()
  next_move_scores &amp;lt;- vector(length = length(next_moves))
  for (i in 1:length(next_moves)) {
    chess_game$move(next_moves[i])
    # To ensure fast execution of the minimax function we select a depth of 1
    # This depth can be increased to enable stronger play at the expense of longer runtime
    next_move_scores[i] &amp;lt;- minimax_scoring(chess_game, 1)
    chess_game$undo()
  }

  # For white return the move with maximum score
  # For black return the move with minimum score
  # If the optimal score is achieved by multiple moves, select one at random
  # This random selection from the optimal moves adds some variability to the play
  if (chess_game$turn() == &amp;quot;w&amp;quot;) {
    return(sample(next_moves[which(next_move_scores == max(next_move_scores))], size = 1))
  } else {
    return(sample(next_moves[which(next_move_scores == min(next_move_scores))], size = 1))
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The function &lt;code&gt;get_minimax_move&lt;/code&gt; defines the complete logic for our computer chess player. We are now ready to test the performance of our algorithm.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;testing-our-r-minimax-chess-engine&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Testing our R minimax chess engine&lt;/h2&gt;
&lt;p&gt;Let’s first test the performance of our minimax-based chess engine by letting it play 10 games as white and 10 games as black against the random move generator we defined at the beginning of this article. If everything works as expected then our engine should win every time:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Function that takes a side as input (&amp;quot;w&amp;quot; or &amp;quot;b&amp;quot;) and plays 10 games
# The selected side will choose moves based on the minimax algorithm
# The opponent will use the random move generator
play_10_games &amp;lt;- function(minimax_player) {
  game_results &amp;lt;- vector(length = 10)
  for (i in 1:10) {
    chess_game &amp;lt;- Chess$new()
    while (!chess_game$game_over()) {
      if (chess_game$turn() == minimax_player) {
        # Selected player uses the minimax strategy
        chess_game$move(get_minimax_move(chess_game))
      } else {
        # Opponent uses the random move generator
        chess_game$move(get_random_move(chess_game))
      }
    }
    # Record the result of the current finished game
    # If mate: the losing player is recorded
    # If draw: record a 0
    if (chess_game$in_checkmate()) {
      game_results[i] &amp;lt;- chess_game$turn()
    } else {
      game_results[i] &amp;lt;- &amp;quot;0&amp;quot;
    }
  }

  # Print the outcome of the 10 games
  print(table(game_results))
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;White wins every game by playing the minimax strategy against the random move generator:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;play_10_games(&amp;quot;w&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## game_results
##  b 
## 10&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Black also wins every game as the minimax player against random white moves:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;play_10_games(&amp;quot;b&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## game_results
##  w 
## 10&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This simple experiment shows that our minimax chess engine is indeed more powerful than a random move generator, but this is a fairly low bar. I have also tested this program against multiple chess apps and it was able to win games against opponents playing at a casual difficulty level. Increasing the minimax depth leads to stronger play, but evaluating more than four moves in advance was not feasible on my computer due to long runtimes.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;conclusion-and-next-steps&#34; class=&#34;section level2&#34;&gt;
&lt;h2&gt;Conclusion and next steps&lt;/h2&gt;
&lt;p&gt;Overall this simple R chess engine is fun to play against for a beginner or casual player, and writing it was a great way to practice the minimax algorithm. Numerous improvements can still be made.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Some updates that I plan to discuss in future posts are:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Implement &lt;a href=&#34;https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning&#34;&gt;alpha-beta pruning&lt;/a&gt; to decrease the number of positions evaluated by minimax.&lt;/li&gt;
&lt;li&gt;Use &lt;a href=&#34;https://en.wikipedia.org/wiki/Negamax&#34;&gt;negamax&lt;/a&gt; to further simplify the code.&lt;/li&gt;
&lt;li&gt;Leverage neural networks to define a better position evaluation function. The &lt;a href=&#34;https://cran.r-project.org/web/packages/tensorflow/index.html&#34;&gt;tensorflow&lt;/a&gt; and &lt;a href=&#34;https://cran.r-project.org/web/packages/keras/index.html&#34;&gt;keras&lt;/a&gt; R packages make it possible to build very flexible neural networks within R.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Programming a simple chess engine is an exciting journey through the many machine learning capabilities offered by R. Looking forward to the next steps!&lt;/strong&gt;&lt;/p&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>How to write bubble sort in R</title>
      <link>https://www.codertime.org/r-how-to-write-bubble-sort/</link>
      <pubDate>Sat, 25 Jun 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-how-to-write-bubble-sort/</guid>
      <description>


&lt;p&gt;&lt;strong&gt;Topics covered:&lt;/strong&gt; number operations, vector operations, sorting algorithms&lt;/p&gt;
&lt;div id=&#34;getting-started&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;Getting started&lt;/h2&gt;
&lt;p&gt;The bubble sort algorithm works by swapping neighboring entries of an input vector if they are not in the desired order. This process is repeated until no more swaps are necessary: the vector is already sorted.&lt;/p&gt;
&lt;p&gt;For example, we want to sort the vector 4, 3, 2, 1 in increasing order using bubble sort. The algorithm will perform the following rearrangements of our input:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Input&lt;/strong&gt;: 4, 3, 2, 1&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Intermediary step&lt;/strong&gt; (first pass through the vector): 3, 4, 2, 1&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Intermediary step&lt;/strong&gt; (first pass through the vector): 3, 2, 4, 1&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Intermediary step&lt;/strong&gt; (first pass through the vector): 3, 2, 1, 4&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Intermediary step&lt;/strong&gt; (second pass through the vector): 2, 3, 1, 4&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Intermediary step&lt;/strong&gt; (second pass through the vector): 2, 1, 3, 4&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Final step&lt;/strong&gt; (third pass through the vector): 1, 2, 3, 4&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&#34;the-bubble-sort-implementation&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;The bubble sort implementation&lt;/h2&gt;
&lt;p&gt;Let’s write a bubble sort function in R that arranges a numeric vector of two or more elements in increasing order:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Input: numeric vector of two or more elements
bubble_sort &amp;lt;- function(x) {
  swap_performed &amp;lt;- TRUE
  # Repeat the algorithm until no more swaps are performed
  while (swap_performed) {
    swap_performed &amp;lt;- FALSE
    # Check if any swaps are necessary
    for (i in 1:(length(x) - 1)) {
      if (x[i] &amp;gt; x[i + 1]) {
        # Swap elements that are not in increasing order
        tmp &amp;lt;- x[i]
        x[i] &amp;lt;- x[i + 1]
        x[i + 1] &amp;lt;- tmp
        # Now record that a swap was performed
        # This requests another pass through the while loop
        swap_performed &amp;lt;- TRUE
      }
    }
  }
  # Output: the vector sorted in increasing order
  return(x)
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div id=&#34;testing-our-implementation&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;Testing our implementation&lt;/h2&gt;
&lt;p&gt;We can now test our bubble sort function on a few random input vectors:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;for (i in 1:4) {
  x &amp;lt;- sample(1:10)
  cat(&amp;quot;Input: &amp;quot;, x, &amp;quot;\n&amp;quot;)
  cat(&amp;quot;Output: &amp;quot;, bubble_sort(x), &amp;quot;\n&amp;quot;)
}&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Input:  5 10 8 9 2 6 4 1 7 3 
## Output:  1 2 3 4 5 6 7 8 9 10 
## Input:  6 4 9 2 5 7 10 8 1 3 
## Output:  1 2 3 4 5 6 7 8 9 10 
## Input:  9 3 6 10 8 7 2 4 5 1 
## Output:  1 2 3 4 5 6 7 8 9 10 
## Input:  10 3 2 4 9 1 7 5 6 8 
## Output:  1 2 3 4 5 6 7 8 9 10&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;All output vectors are sorted in increasing order as expected.&lt;/p&gt;
&lt;p&gt;We can also add a line to our program that prints the current state of the vector after each swap:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Input: numeric vector of two or more elements
bubble_sort &amp;lt;- function(x) {
  swap_performed &amp;lt;- TRUE
  # Repeat the algorithm until no more swaps are performed
  while (swap_performed) {
    swap_performed &amp;lt;- FALSE
    # Check if any swaps are necessary
    for (i in 1:(length(x) - 1)) {
      if (x[i] &amp;gt; x[i + 1]) {
        # Swap elements that are not in increasing order
        tmp &amp;lt;- x[i]
        x[i] &amp;lt;- x[i + 1]
        x[i + 1] &amp;lt;- tmp
        # Now record that a swap was performed
        # This requests another pass through the while loop
        swap_performed &amp;lt;- TRUE
        # Print the current state of our vector
        cat(&amp;quot;Current state: &amp;quot;, x, &amp;quot;\n&amp;quot;)
      }
    }
  }
  # Output: the vector sorted in increasing order
  return(x)
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This allows us to track the progress of bubble sort as it orders the input vector:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;bubble_sort(c(1, 3, 5, 2, 4, 6))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## Current state:  1 3 2 5 4 6 
## Current state:  1 3 2 4 5 6 
## Current state:  1 2 3 4 5 6&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1 2 3 4 5 6&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Exercise 8: recursive functions in R</title>
      <link>https://www.codertime.org/r-programming-exercise-recursive-functions-fibonacci-8/</link>
      <pubDate>Mon, 20 Jun 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-programming-exercise-recursive-functions-fibonacci-8/</guid>
      <description>


&lt;p&gt;The recursive R function &lt;code&gt;FUN&lt;/code&gt; is defined as:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN &amp;lt;- function(x) {
  if (x == 0 | x == 1) {
    return(x)
  } else {
    return(FUN(x - 1) + FUN(x - 2))
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What is the value of &lt;code&gt;x&lt;/code&gt; that leads to the following output:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 6765&lt;/code&gt;&lt;/pre&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;To help answer this question we first notice that the recursive function FUN defines the &lt;a href=&#34;https://en.wikipedia.org/wiki/Fibonacci_number#Definition&#34;&gt;Fibonacci sequence&lt;/a&gt;. So we are searching for an integer &lt;code&gt;x&lt;/code&gt; &amp;gt;= 0 that corresponds to the Fibonacci number 6765. To solve the puzzle we can either look up the &lt;a href=&#34;http://oeis.org/A000045/list&#34;&gt;first few terms&lt;/a&gt; of the Fibonacci sequence or use our function definition to run through some inputs.&lt;/p&gt;
&lt;p&gt;To avoid calling FUN manually for different values we can define a vectorized version of the function and run it on the integer inputs between 0 and 20:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  vector_FUN &amp;lt;- Vectorize(FUN)
  vector_FUN(0:20)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ##  [1]    0    1    1    2    3    5    8   13   21   34
  ## [11]   55   89  144  233  377  610  987 1597 2584 4181
  ## [21] 6765&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The answer we get is x = 20:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  x &amp;lt;- 20
  FUN(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 6765&lt;/code&gt;&lt;/pre&gt;
&lt;/details&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Exercise 7: R string processing</title>
      <link>https://www.codertime.org/r-programming-exercise-string-processing-7/</link>
      <pubDate>Sun, 05 Jun 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-programming-exercise-string-processing-7/</guid>
      <description>


&lt;p&gt;Find a function &lt;code&gt;FUN&lt;/code&gt; that leads to the following output:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(&amp;quot;mile&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;e&amp;quot; &amp;quot;i&amp;quot; &amp;quot;l&amp;quot; &amp;quot;m&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(&amp;quot;lime&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;e&amp;quot; &amp;quot;i&amp;quot; &amp;quot;l&amp;quot; &amp;quot;m&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(&amp;quot;camel&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;a&amp;quot; &amp;quot;c&amp;quot; &amp;quot;e&amp;quot; &amp;quot;l&amp;quot; &amp;quot;m&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(paste(sample(letters), collapse = &amp;quot;&amp;quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1] &amp;quot;a&amp;quot; &amp;quot;b&amp;quot; &amp;quot;c&amp;quot; &amp;quot;d&amp;quot; &amp;quot;e&amp;quot; &amp;quot;f&amp;quot; &amp;quot;g&amp;quot; &amp;quot;h&amp;quot; &amp;quot;i&amp;quot; &amp;quot;j&amp;quot; &amp;quot;k&amp;quot; &amp;quot;l&amp;quot; &amp;quot;m&amp;quot;
## [14] &amp;quot;n&amp;quot; &amp;quot;o&amp;quot; &amp;quot;p&amp;quot; &amp;quot;q&amp;quot; &amp;quot;r&amp;quot; &amp;quot;s&amp;quot; &amp;quot;t&amp;quot; &amp;quot;u&amp;quot; &amp;quot;v&amp;quot; &amp;quot;w&amp;quot; &amp;quot;x&amp;quot; &amp;quot;y&amp;quot; &amp;quot;z&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; aim to keep the answer simple. The main logic of the function can often be summarized in a single line of R code.&lt;/p&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;We can write the function as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(sort(strsplit(x, split = &amp;quot;&amp;quot;)[[1]]))
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This function splits the input string into single characters and then performs an alphabetical sort. For example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  x &amp;lt;- &amp;quot;camel&amp;quot;
  strsplit(x, split = &amp;quot;&amp;quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [[1]]
  ## [1] &amp;quot;c&amp;quot; &amp;quot;a&amp;quot; &amp;quot;m&amp;quot; &amp;quot;e&amp;quot; &amp;quot;l&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  sort(strsplit(x, split = &amp;quot;&amp;quot;)[[1]])&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] &amp;quot;a&amp;quot; &amp;quot;c&amp;quot; &amp;quot;e&amp;quot; &amp;quot;l&amp;quot; &amp;quot;m&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;/details&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Beginner R lesson: arithmetic operations (part 1)</title>
      <link>https://www.codertime.org/r-programming-lesson-arithmetics-introduction-1/</link>
      <pubDate>Fri, 03 Jun 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-programming-lesson-arithmetics-introduction-1/</guid>
      <description>


&lt;p&gt;&lt;strong&gt;Topics covered:&lt;/strong&gt; number operations, defining and using variables&lt;/p&gt;
&lt;div id=&#34;getting-started&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;Getting started&lt;/h2&gt;
&lt;p&gt;We start our programming journey by exploring how R lets us perform numerical calculations. We will first review some practical aspects relating to syntax and then dive into multiple example programs that provide a deeper insight into the language and R’s powerful number-crunching abilities.&lt;/p&gt;
&lt;p&gt;Working with numbers is an essential part of many programs that we will create and showcases some basic syntax and functionality built into the R language. This lesson does not require any prior knowledge of R and is designed as a first contact with the language, so let’s dive in!&lt;/p&gt;
&lt;p&gt;At a fundamental level R can serve as a powerful interactive calculator and the syntax we use for most arithmetic operations is fairly intuitive:&lt;/p&gt;
&lt;p&gt;Addition and subtraction:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;99 + 1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 100&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;101 - 1&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 100&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Multiplication and division:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;100 * 2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 200&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;100 / 3&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 33.33333&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Powers:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;10^2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 100&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Parentheses to define the order of operations:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;(99 + 1) / 2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 50&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can also define variables that store numerical or other types of data via an assignment operator:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;a &amp;lt;- 100
a&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 100&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;b &amp;lt;- 100 / 2
b&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 50&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Arithmetic operations can now be run using the variables we defined:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;a + b&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 150&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;a^b&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1e+100&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can also test whether two numbers are equal, which will be helpful in future lessons:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;a&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 100&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;b&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 50&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;a == b&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] FALSE&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;a == b * 2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Throughout this lesson we will also include comments in our code to clarify intended functionality and make the programs more easily readable. Everything in a line after the &lt;code&gt;#&lt;/code&gt; symbol will be treated by R as a comment and will not be executed:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# This is a comment
10^2 + 10^1 + 10^0 # The code before this comment will execute&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 111&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The concepts presented so far will serve as basic building blocks for more complex programs. Let’s see these topics in action by working through some examples.&lt;/p&gt;
&lt;/div&gt;
&lt;div id=&#34;practice-computing-sums-of-consecutive-integers&#34; class=&#34;section level2 unnumbered&#34;&gt;
&lt;h2&gt;Practice: computing sums of consecutive integers&lt;/h2&gt;
&lt;p&gt;Many mathematical formulas have been constructed around sums of integer numbers. One such formula computes the sum of all integers between 1 and any integer &lt;code&gt;n&lt;/code&gt; greater than or equal to 1:&lt;/p&gt;
&lt;p&gt;1 + … + n = n(n+1)/2 for any integer n &amp;gt;= 1.&lt;/p&gt;
&lt;p&gt;Let’s use R to implement and test this formula for a few values of &lt;code&gt;n&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;n &amp;lt;- 10
# Compute sum via formula:
n * (n + 1) / 2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 55&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;# Compute sum by explicit addition:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 55&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As expected, computing this sum by explicitly adding each number together gives us the same answer as using the formula. We can also formally test if the outputs are equal without even looking at the actual results:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;n * (n + 1) / 2 == 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] TRUE&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now that we have implemented this formula in R we can easily compute sums for new values of &lt;code&gt;n&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;n &amp;lt;- 100
n * (n + 1) / 2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 5050&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;n &amp;lt;- 1000
n * (n + 1) / 2&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 500500&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Re-using the formula for different values of n is much easier and less error-prone than writing out the whole sum term by term, especially if n becomes large, but formulas are not always available to simplify repetitive computations. We will see in future lessons that R offers powerful ways to enable such tasks through loops and vector operations.&lt;/p&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
&lt;/div&gt;
</description>
    </item>
    
    <item>
      <title>Exercise 6: R numeric calculations</title>
      <link>https://www.codertime.org/r-programming-exercise-numeric-operations-6/</link>
      <pubDate>Thu, 02 Jun 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-programming-exercise-numeric-operations-6/</guid>
      <description>


&lt;p&gt;Find a function &lt;code&gt;FUN&lt;/code&gt; that leads to the following output:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;curve(FUN, from = -2, to = 2, n = 1000)
grid()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/r-programming-exercise-numeric-operations-6/index_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; aim to keep the answer simple. The main logic of the function can often be summarized in a single line of R code.&lt;/p&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;We can write the function as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(abs(x) %% 1)
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This function returns the fractional part of the absolute value of its input. For example:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(12.345)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 0.345&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(-0.1234)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 0.1234&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;FUN&lt;/code&gt; can be defined equivalently as:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(abs(x) - floor(abs(x)))
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To check that this function is indeed a solution to the puzzle we can redraw the plot:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  curve(FUN, from = -2, to = 2, n = 1000)
  grid()&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&#34;https://www.codertime.org/r-programming-exercise-numeric-operations-6/index_files/figure-html/unnamed-chunk-7-1.png&#34; width=&#34;672&#34; /&gt;
&lt;/details&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Exercise 5: R matrix operations</title>
      <link>https://www.codertime.org/r-programming-exercise-matrix-operations-5/</link>
      <pubDate>Wed, 01 Jun 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-programming-exercise-matrix-operations-5/</guid>
      <description>


&lt;p&gt;Find a function &lt;code&gt;FUN&lt;/code&gt; that leads to the following output:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;a &amp;lt;- matrix(1:36, nrow = 6)
b &amp;lt;- matrix(1:25, nrow = 5)
a&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    7   13   19   25   31
## [2,]    2    8   14   20   26   32
## [3,]    3    9   15   21   27   33
## [4,]    4   10   16   22   28   34
## [5,]    5   11   17   23   29   35
## [6,]    6   12   18   24   30   36&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(a)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 16 17 18 19 20 21&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;b&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    6   11   16   21
## [2,]    2    7   12   17   22
## [3,]    3    8   13   18   23
## [4,]    4    9   14   19   24
## [5,]    5   10   15   20   25&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(b)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 11 12 13 14 15&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; aim to keep the answer simple. The main logic of the function can often be summarized in a single line of R code.&lt;/p&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;We can write the function as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(apply(x, MARGIN = 1, FUN = median))
  }&lt;/code&gt;&lt;/pre&gt;
This function computes the median for each row of the input matrix.
&lt;/details&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Exercise 4: R trigonometric functions</title>
      <link>https://www.codertime.org/r-programming-exercise-trigonometric-functions-4/</link>
      <pubDate>Tue, 31 May 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-programming-exercise-trigonometric-functions-4/</guid>
      <description>


&lt;p&gt;Find a function &lt;code&gt;FUN&lt;/code&gt; that leads to the following output:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;curve(FUN, from = -10, to = 10, col = &amp;quot;red&amp;quot;, ylim = c(-2, 2))
curve(sin, add = TRUE)
grid()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/r-programming-exercise-trigonometric-functions-4/index_files/figure-html/unnamed-chunk-3-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; aim to keep the answer simple. The main logic of the function can often be summarized in a single line of R code.&lt;/p&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer 1: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;We can write the function as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(sin(x + pi / 2))
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We then get:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  curve(FUN, from = -10, to = 10, col = &amp;quot;red&amp;quot;, ylim = c(-2, 2))
  curve(sin, add = TRUE)
  grid()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/r-programming-exercise-trigonometric-functions-4/index_files/figure-html/unnamed-chunk-5-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/details&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer 2: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;We can use various trigonometric identities to derive more solutions to this puzzle. For example:&lt;/p&gt;
&lt;p&gt;sin(x + pi/2) = cos(x)&lt;/p&gt;
&lt;p&gt;&lt;code&gt;FUN&lt;/code&gt; can then be defined as:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(cos(x))
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can confirm that this function solves the puzzle:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  curve(FUN, from = -10, to = 10, col = &amp;quot;red&amp;quot;, ylim = c(-2, 2))
  curve(sin, add = TRUE)
  grid()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&#34;https://www.codertime.org/r-programming-exercise-trigonometric-functions-4/index_files/figure-html/unnamed-chunk-7-1.png&#34; width=&#34;672&#34; /&gt;&lt;/p&gt;
&lt;/details&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Exercise 3: R numeric calculations</title>
      <link>https://www.codertime.org/r-programming-exercise-numeric-operations-3/</link>
      <pubDate>Mon, 30 May 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-programming-exercise-numeric-operations-3/</guid>
      <description>


&lt;p&gt;Find a function &lt;code&gt;FUN&lt;/code&gt; that leads to the following output:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;FUN(pi) - FUN(exp(1))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; aim to keep the answer simple. The main logic of the function can often be summarized in a single line of R code.&lt;/p&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;We can write the function as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(floor(x))
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The R function &lt;code&gt;floor&lt;/code&gt; returns the largest integer not greater than the input argument:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  pi&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 3.141593&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(pi)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 3&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  exp(1)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 2.718282&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(exp(1))&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 2&lt;/code&gt;&lt;/pre&gt;
&lt;/details&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Exercise 2: R vector operations</title>
      <link>https://www.codertime.org/r-programming-exercise-vector-operations-2/</link>
      <pubDate>Sun, 29 May 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-programming-exercise-vector-operations-2/</guid>
      <description>


&lt;p&gt;Find a function &lt;code&gt;FUN&lt;/code&gt; that leads to the following output:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- sample(1:10)
FUN(x) - FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;##  [1] 11 11 11 11 11 11 11 11 11 11&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; aim to keep the answer simple. The main logic of the function can often be summarized in a single line of R code.&lt;/p&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer 1: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;We can write the function as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(sort(x))
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on this definition of &lt;code&gt;FUN&lt;/code&gt; we get:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ##  [1]  1  2  3  4  5  6  7  8  9 10&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ##  [1] -10  -9  -8  -7  -6  -5  -4  -3  -2  -1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which fulfills the puzzle condition:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(x) - FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ##  [1] 11 11 11 11 11 11 11 11 11 11&lt;/code&gt;&lt;/pre&gt;
&lt;/details&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer 2: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;Another possible definition of &lt;code&gt;FUN&lt;/code&gt; that builds on Puzzle 1 is:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(rep(max(x), times = length(x)))
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on this definition of &lt;code&gt;FUN&lt;/code&gt; we get:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ##  [1] 10 10 10 10 10 10 10 10 10 10&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ##  [1] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which fulfills the puzzle condition:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(x) - FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ##  [1] 11 11 11 11 11 11 11 11 11 11&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we have seen in exercise 1 the &lt;code&gt;max&lt;/code&gt; can also be replaced with &lt;code&gt;min&lt;/code&gt; and the result still holds:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(rep(min(x), times = length(x)))
  }
  FUN(x) - FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ##  [1] 11 11 11 11 11 11 11 11 11 11&lt;/code&gt;&lt;/pre&gt;
&lt;/details&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Exercise 1: R vector operations</title>
      <link>https://www.codertime.org/r-programming-exercise-vector-operations-1/</link>
      <pubDate>Sat, 28 May 2022 00:00:00 +0000</pubDate>
      
      <guid>https://www.codertime.org/r-programming-exercise-vector-operations-1/</guid>
      <description>


&lt;p&gt;Find a function &lt;code&gt;FUN&lt;/code&gt; that leads to the following output:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;x &amp;lt;- 1:10
FUN(x) - FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;## [1] 11&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; aim to keep the answer simple. The main logic of the function can often be summarized in a single line of R code.&lt;/p&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer 1: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;We can write the function as follows:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(max(x))
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on this definition of &lt;code&gt;FUN&lt;/code&gt; we get:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 10&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] -1&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We finally confirm that this function solves the puzzle:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(x) - FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 11&lt;/code&gt;&lt;/pre&gt;
&lt;/details&gt;
&lt;details&gt;
&lt;summary&gt;
&lt;b&gt;Answer 2: click to reveal&lt;/b&gt;
&lt;/summary&gt;
&lt;p&gt;Another solution to this puzzle is:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN &amp;lt;- function(x) {
    return(min(x))
  }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Based on this definition of &lt;code&gt;FUN&lt;/code&gt; we get:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 1&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] -10&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We confirm that this function solves the puzzle:&lt;/p&gt;
&lt;pre class=&#34;r&#34;&gt;&lt;code&gt;  FUN(x) - FUN(-x)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;  ## [1] 11&lt;/code&gt;&lt;/pre&gt;
&lt;/details&gt;
&lt;p style=&#34;background-color:PapayaWhip; border-width:2px; border-style:solid; border-color:Teal; border-radius:20px; padding:7px&#34;&gt;
&lt;em&gt;For a full collection of R programming tutorials and exercises visit my website at &lt;a href=&#34;https://www.codertime.org/&#34;&gt;&lt;strong&gt;codeRtime.org&lt;/strong&gt;&lt;/a&gt; and the &lt;a href=&#34;https://www.youtube.com/c/codeRtime&#34;&gt;&lt;strong&gt;codeRtime YouTube channel&lt;/strong&gt;&lt;/a&gt;&lt;/em&gt;.
&lt;/p&gt;
</description>
    </item>
    
  </channel>
</rss>
