<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Introduction-to-R Archives - Data Analytics</title>
	<atom:link href="https://dataanalytics.org.uk/category/introduction-to-r/feed/" rel="self" type="application/rss+xml" />
	<link>https://dataanalytics.org.uk/category/introduction-to-r/</link>
	<description>Understanding Data</description>
	<lastBuildDate>Thu, 01 Sep 2022 11:53:31 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.1</generator>

<image>
	<url>https://dataanalytics.org.uk/wp-content/uploads/2019/11/cropped-DA-graph-logo-2019-cyan-600-32x32.png</url>
	<title>Introduction-to-R Archives - Data Analytics</title>
	<link>https://dataanalytics.org.uk/category/introduction-to-r/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Matrix Math</title>
		<link>https://dataanalytics.org.uk/matrix-math-operations-using-r/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=matrix-math-operations-using-r</link>
		
		<dc:creator><![CDATA[gmark]]></dc:creator>
		<pubDate>Thu, 01 Sep 2022 11:53:31 +0000</pubDate>
				<category><![CDATA[Introduction-to-R]]></category>
		<category><![CDATA[chol]]></category>
		<category><![CDATA[Cholensky]]></category>
		<category><![CDATA[cross product]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[determinant]]></category>
		<category><![CDATA[eigenvalue]]></category>
		<category><![CDATA[eigenvector]]></category>
		<category><![CDATA[inner product]]></category>
		<category><![CDATA[Kronecker]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[math functions]]></category>
		<category><![CDATA[matrices]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[outer]]></category>
		<category><![CDATA[outer-product]]></category>
		<category><![CDATA[qr]]></category>
		<category><![CDATA[QR decomposition]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[sad]]></category>
		<category><![CDATA[Singular Value Decomposition]]></category>
		<category><![CDATA[transpose]]></category>
		<guid isPermaLink="false">https://www.dataanalytics.org.uk/?p=39610</guid>

					<description><![CDATA[<p>Matrix Math Operations Using R Matrix math operations using R are easy to conduct using basic math operators such as + - * [&#8230;]</p>
<p>The post <a href="https://dataanalytics.org.uk/matrix-math-operations-using-r/">Matrix Math</a> appeared first on <a href="https://dataanalytics.org.uk">Data Analytics</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1>Matrix Math Operations Using R</h1>
<p>Matrix math operations using R are easy to conduct using basic math operators such as <code>+</code> <code>-</code> <code>*</code> and <code>/</code>. Generally speaking the <code>matrix</code> objects you perform math on must be the same dimensions (that is conformable) as each other but there are exceptions.</p>
<p>There are two kinds of matrix math:</p>
<ul>
<li>Math using a <code>matrix</code> simply as a series of values.</li>
<li>Matrix math using array properties.</li>
</ul>
<p>In the first case you can use <code>R</code> to carry out regular mathematical operations on a <code>matrix</code> (that is a 2-dimensional array). In the second case you use <code>R</code> to conduct &#8220;proper&#8221; matrix math.</p>
<p>This article is not intended to be a detailed treatise on matrix math; think of it more as a rough guide to possibilities. If <code>matrix</code> math is what you need then this might help point you in the right direction.</p>
<p>Here are some of the topics covered:</p>
<ul>
<li><a href="#simple-math">Simple math</a>
<ul>
<li><a href="#identical-dim">Identical dimensions</a></li>
<li><a href="#single-num">Matrix and single numeric</a></li>
<li><a href="#multiple-num">Matrix and multiple numeric</a></li>
<li><a href="#other-ops">Other matrix operations</a></li>
<li><a href="#non-conform">Non-conformable matrices</a></li>
</ul>
</li>
<li><a href="#matrix-math">Matrix math</a>
<ul>
<li><a href="#inner">Inner product</a></li>
<li><a href="#outer">Outer product</a></li>
<li><a href="#kronecker">Kronecker product</a></li>
<li><a href="#diag">Diagonals</a></li>
<li><a href="#eigen">Eigenvalues and Eigenvectors</a></li>
<li><a href="#svd">Singular Value Decomposition</a></li>
<li><a href="#chol">Cholesky decomposition</a></li>
<li><a href="#qr">QR decomposition</a></li>
<li><a href="#det">Determinant</a></li>
<li><a href="#cross">Cross products</a></li>
</ul>
</li>
<li><a href="#misc-tools">Miscellaneous tools</a>
<ul>
<li><a href="#transpose">Transposition</a></li>
<li><a href="#triangles">Upper/lower triangles</a></li>
<li><a href="#row-index">Row/column index</a></li>
</ul>
</li>
</ul>
<h2 id="simple-math">Simple math</h2>
<p>Matrix math operations using R can be fairly simple. In the &#8220;simple&#8221; case you can use a <code>matrix</code> with basic math operators.</p>
<h3 id="identical-dim">Identical dimensions</h3>
<p>The &#8220;simplest&#8221; situation is where you have <code>matrix</code> objects that have the same dimensions.</p>
<pre><code class="language-r" lang="r">x &lt;- <span style="color: #0000ff;">matrix</span>(c(1,1, 3,0, 1,0), ncol = 3))
y &lt;- <span style="color: #0000ff;">matrix</span>(c(0,7, 0,5, 5,0), ncol = 3)
x ; y

     [,1] [,2] [,3]
[1,]    1    3    1
[2,]    1    0    0

     [,1] [,2] [,3]
[1,]    0    0    5
[2,]    7    5    0
</code></pre>
<p>The regular math operators with deal with the calculations:</p>
<pre><code class="language-r" lang="r">x + y
     [,1] [,2] [,3]
[1,]    1    3    6
[2,]    8    5    0

x * y
     [,1] [,2] [,3]
[1,]    0    0    5
[2,]    7    0    0

x / y
          [,1] [,2] [,3]
[1,]       Inf  Inf  0.2
[2,] 0.1428571    0  NaN

x - y
     [,1] [,2] [,3]
[1,]    1    3   -4
[2,]   -6   -5    0
</code></pre>
<p>In the preceding example 2 <code>matrix</code> objects were used but there is no reason why you cannot have more, as long as they all have the same dimensions.</p>
<h3 id="">Matrix and a single numeric</h3>
<p>If you have a <code>matrix</code> you can also use the basic operators with a single value:</p>
<pre><code class="language-r" lang="r">x * 4.5
     [,1] [,2] [,3]
[1,]  4.5 13.5  4.5
[2,]  4.5  0.0  0.0

y / 2
     [,1] [,2] [,3]
[1,]  0.0  0.0  2.5
[2,]  3.5  2.5  0.0
</code></pre>
<h3 id="multiple-num">Matrix and multiple numeric</h3>
<p>You can think of a <code>matrix</code> as a <code>vector</code> of values that happens to be split into rows and columns. This means that you can carry out math operations with a <code>matrix</code> and a <code>vector</code> of values, as long as the recursive process &#8220;fits&#8221; (i.e. is conformable).</p>
<p>In practical terms you can carry out a math operation between a <code>matrix</code> and a <code>vector</code> if the length of the <code>matrix</code> is divisible by the length of the <code>vector</code> exactly (i.e. producing an integer).</p>
<p>In the following example, the <code>matrix</code> has 6 elements and therefore any <code>vector</code> would have to contain 1, 2, or 3 elements. If your <code>vector</code> is too long it is truncated and you get a warning.</p>
<pre><code class="language-r" lang="r">x
     [,1] [,2] [,3]
[1,]    1    3    1
[2,]    1    0    0

<span style="color: #0000ff;">length</span>(x)
[1] 6

x * 2:4
     [,1] [,2] [,3]
[1,]    2   12    3
[2,]    3    0    0

<span style="color: #808000;"># Long vectors are truncated with a warning</span>
x + 1:4
     [,1] [,2] [,3]
[1,]    2    6    2
[2,]    3    4    2

Warning message:
In x + 1:4 :
  longer object length is not a multiple of shorter object length
</code></pre>
<p>It can help to see your <code>matrix</code> as a <code>vector</code>:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">c</span>(x)
[1] 1 1 3 0 1 0

<span style="color: #0000ff;">c</span>(x) * 2:4
[1]  2  3 12  0  3  0

<span style="color: #0000ff;">c</span>(x) + 1:4
[1] 2 3 6 4 2 2

Warning message:
In c(x) + 1:4 :
  longer object length is not a multiple of shorter object length
</code></pre>
<p>Note that <code>c(x)</code> was used in the example but <code>as.numeric(x)</code> would also work.</p>
<h3 id="other-ops">Other matrix math operations</h3>
<p>Many math functions that can operate on a <code>vector</code> will be able to work with a <code>matrix</code>. For example:</p>
<pre><code class="language-r" lang="r">xx
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

<span style="color: #0000ff;">log</span>(xx)
         [,1]      [,2]     [,3]
[1,] 0.000000 0.6931472 1.098612
[2,] 1.386294 1.6094379 1.791759

<span style="color: #0000ff;">cos</span>(xx)
           [,1]       [,2]       [,3]
[1,]  0.5403023 -0.4161468 -0.9899925
[2,] -0.6536436  0.2836622  0.9601703

<span style="color: #0000ff;">sqrt</span>(xx)
     [,1]     [,2]     [,3]
[1,]    1 1.414214 1.732051
[2,]    2 2.236068 2.449490
</code></pre>
<hr />
<h3 id="non-conform">Non-conformable matrices</h3>
<p>When you have two <code>matrix</code> objects of different dimensions you get an error. This example shows a single dimension <code>matrix</code>:</p>
<pre><code class="language-r" lang="r">yy &lt;- <span style="color: #0000ff;">matrix</span>(c(40,100), ncol = 1)
yy
     [,1]
[1,]   10
[2,]  100

x * yy
Error in x * yy : non-conformable arrays
</code></pre>
<p>In this case the <code>matrix</code> can be converted to a <code>vector</code> resulting in 2 elements. This is divisible by the number of elements in the first <code>matrix</code> and permits matrix math:</p>
<pre><code class="language-r" lang="r">x * <span style="color: #0000ff;">c</span>(yy)
     [,1] [,2] [,3]
[1,]   10   30   10
[2,]  100    0    0

x + <span style="color: #0000ff;">c</span>(yy)
     [,1] [,2] [,3]
[1,]   11   13   11
[2,]  101  100  100
</code></pre>
<p>There are other solutions for this case:</p>
<pre><code class="language-r" lang="r">xx * <span style="color: #0000ff;">c</span>(yy)
<span style="color: #0000ff;">sweep</span>(xx, 1, yy, `*`)
<span style="color: #0000ff;">apply</span>(xx, 2, <span style="color: #0000ff;">function</span>(x) x * yy)
xx * yy[,1]
xx * yy[<span style="color: #0000ff;">row</span>(xx),]
</code></pre>
<p>These solutions work for any of the math operators <code>+</code> <code>-</code> <code>*</code> and <code>/</code>.</p>
<hr />
<h2 id="matrix-math">Matrix Mathematics</h2>
<p>Matrix math operations using R involve more than just simple math. In mathematics <code>matrix</code> math is a substantial topic. Using <code>R</code> you can carry out various matrix math computations. These include:</p>
<ul>
<li>Inner product <code>%*%</code></li>
<li>Outer product <code>outer()</code> and <code>%o%</code></li>
<li>Kronecker product <code>kronecker()</code> and <code>%x%</code></li>
<li>Matrix diagonals <code>diag()</code></li>
<li>Eigenvalues <code>eigen()</code></li>
<li>Singular Value Decomposition <code>svd()</code></li>
<li>Cholesky (Choleski) decomposition <code>chol()</code></li>
<li>QR decomposition <code>qr()</code></li>
<li>Determinant <code>det()</code></li>
<li>Cross-product <code>crossprod()</code> and <code>tcrossprod()</code></li>
<li>Transposition <code>t()</code></li>
<li>Upper/lower triangles <code>upper.tri()</code> and <code>lower.tri()</code></li>
<li>Row/column index <code>row()</code> and <code>col()</code></li>
</ul>
<h3 id="inner">Inner product</h3>
<p>Standard matrix multiplication (or inner product) is a way to multiply two <code>matrix</code> objects. You use the <code>%*%</code> operator in <code>R</code>to execute the math.</p>
<pre><code class="language-r" lang="r">X %*% Y
</code></pre>
<p>In general if the number of columns of the first <code>matrix</code> equals the number of rows of the second <code>matrix</code> then you should be able to use the matrix-math operator <code>%*%</code> to multiply:</p>
<pre><code class="language-r" lang="r">X &lt;- <span style="color: #0000ff;">matrix</span>(c(2,7,4,8,5,9), ncol = 3)
Y &lt;- <span style="color: #0000ff;">matrix</span>(c(1,3,4,6,1,2), ncol = 2)

X ; Y
     [,1] [,2] [,3]
[1,]    2    4    5
[2,]    7    8    9

     [,1] [,2]
[1,]    1    6
[2,]    3    1
[3,]    4    2

X %*% Y
     [,1] [,2]
[1,]   34   26
[2,]   67   68
</code></pre>
<h3 id="outer">Outer product</h3>
<p>The outer product is a <code>matrix</code> operation that takes a <code>matrix</code> (or <code>vector</code> or <code>array</code>) and applies a function to it, with a second <code>matrix</code> (or a <code>vector</code> or <code>array</code>) as an argument. There are two options in <code>R</code>:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">outer</span>(X, Y, FUN = "*", ...)
X %o% Y
</code></pre>
<p>The <code>outer()</code> command allows any maths function, with the default being <code>*</code>. Essentially <code>X</code> and <code>Y</code> are the main arguments (you can pass additional parameters too). The <code>%o%</code> operator (the letter o) is a convenience function for multiply (i.e. <code>FUN = "*"</code>) so you end up specifying <code>X</code> multiplied by <code>Y</code>.</p>
<p>Use two vectors and the result is a <code>matrix</code> with dimensions determined by the length of the vectors:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">outer</span>(1:3, 1:3)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    4    6
[3,]    3    6    9
</code></pre>
<p>You can use different function, and use <code>Y</code> as a parameter passed to <code>FUN</code>, in the following example <code>Y</code> specifies the <code>base</code> for the <code>log</code>:</p>
<pre><code class="language-r" lang="r">m
     [,1] [,2]
[1,]    5    1
[2,]    1    3

<span style="color: #0000ff;">outer</span>(m, Y = 2, FUN = log)
, , 1

         [,1]     [,2]
[1,] 2.321928 0.000000
[2,] 0.000000 1.584963
</code></pre>
<p>Essentially what happens is that the second <code>matrix</code> is converted to a <code>vector</code> and this is &#8220;applied&#8221; to the first <code>matrix</code> using the function specified. Each element of the second <code>matrix</code> is applied in turn, and the result is an <code>array</code> with multiple dimensions. In the following example the first <code>matrix</code> is 2&#215;2 and so is the second, so the result has dimensions of: <code>2, 2, 2, 2</code></p>
<pre><code class="language-r" lang="r">A
     [,1] [,2]
[1,]    4   -1
[2,]    1    3

m
     [,1] [,2]
[1,]    5    1
[2,]    1    3

<span style="color: #0000ff;">outer</span>(A, m, FUN = "+")
, , 1, 1

     [,1] [,2]
[1,]    9    4
[2,]    6    8

, , 2, 1

     [,1] [,2]
[1,]    5    0
[2,]    2    4

, , 1, 2

     [,1] [,2]
[1,]    5    0
[2,]    2    4

, , 2, 2

     [,1] [,2]
[1,]    7    2
[2,]    4    6

<span style="color: #808000;"># Get identical result using a vector</span>
<span style="color: #0000ff;">outer</span>(A, c(5,1,1,3), FUN = "+")
</code></pre>
<h3 id="kronecker">Kronecker product</h3>
<p>The Kronecker matrix product is similar to the outer product but the result is a single <code>array</code> with dimensions equal to <code>dim(X)</code> x <code>dim(Y)</code>.</p>
<pre><code><span style="color: #0000ff;">kronecker</span>(X, Y, FUN = "*", ...)
X %x% Y
</code></pre>
<p>The <code>kronecker()</code> command allows any function to be used, whist the alias <code>%x%</code> is for multiply (i.e. <code>FUN = "*"</code>).</p>
<pre><code class="language-r" lang="r">m
     [,1] [,2]
[1,]    5    1
[2,]    1    3

m %x% 2
     [,1] [,2]
[1,]   10    2
[2,]    2    6
</code></pre>
<p>When your second array has &gt;1 dimension, the result has dimensions equal to <code>dim(X)</code> x <code>dim(Y)</code>.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">kronecker</span>(m, 2:3, FUN = "+")
     [,1] [,2]
[1,]    7    3
[2,]    8    4
[3,]    3    5
[4,]    4    6

xx
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

yy
     [,1]
[1,]   10
[2,]  100

<span style="color: #0000ff;">kronecker</span>(xx, yy)
     [,1] [,2] [,3]
[1,]   10   20   30
[2,]  100  200  300
[3,]   40   50   60
[4,]  400  500  600
</code></pre>
<h3 id="diag">Diagonals</h3>
<p>A <code>matrix</code> diagonal is more or less what it sounds like! Matrix diagonals are used in various branches of matrix math. In <code>R</code>you can use the <code>diag()</code> function to extract or create <code>matrix</code> diagonals.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">diag</span>(x = 1, nrow, ncol, names = TRUE)
<span style="color: #0000ff;">diag</span>(x) &lt;- value
</code></pre>
<p>There are 4 main uses for <code>diag()</code>:</p>
<ol>
<li>To extract the diagonal from <code>x</code> (a <code>matrix</code>).</li>
<li>To make an identity <code>matrix</code> by specifying <code>nrow</code>.</li>
<li>To make an identity <code>matrix</code> by specifying <code>x</code> as a scalar.</li>
<li>To make a <code>matrix</code> with specified diagonals.</li>
</ol>
<p>You can also assign diagonal values to an existing <code>matrix</code>.</p>
<h4>Extract diagonals</h4>
<p>To extract the diagonals from a <code>matrix</code> you simply specify the <code>matrix</code>:</p>
<pre><code class="language-r" lang="r">C
     [,1] [,2] [,3]
[1,]    3    1   -5
[2,]    2    0    4
[3,]    1    6    3

<span style="color: #0000ff;">diag</span>(C)
[1] 3 0 3
</code></pre>
<p>If the <code>matrix</code> is not square you get the diagonals starting from the top-left:</p>
<pre><code class="language-r" lang="r">E
     [,1] [,2] [,3]
[1,]   -3    2    0
[2,]    0    5   -1

<span style="color: #0000ff;">diag</span>(E)
[1] -3  5
</code></pre>
<h4>Identity matrix from nrow</h4>
<p>If you omit <code>x</code> and specify <code>nrow</code> you will return an identity matrix, that is one where the diagonals are <code>1</code> and the other elements are <code>0</code>. You may also give <code>ncol</code> to create a non-square <code>matrix</code> (note that <code>ncol</code> may be larger or smaller than <code>nrow</code>):</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">diag</span>(nrow = 4)
     [,1] [,2] [,3] [,4]
[1,]    1    0    0    0
[2,]    0    1    0    0
[3,]    0    0    1    0
[4,]    0    0    0    1

<span style="color: #0000ff;">diag</span>(nrow = 4, ncol = 3)
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1
[4,]    0    0    0

<span style="color: #0000ff;">diag</span>(nrow = 4, ncol = 6)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    0    0    0    0    0
[2,]    0    1    0    0    0    0
[3,]    0    0    1    0    0    0
[4,]    0    0    0    1    0    0
</code></pre>
<h4>Identity matrix from scalar</h4>
<p>If you specify <code>x</code> as a scalar (single value) you return an identity <code>matrix</code> with diagonals of <code>1</code> and with dimensions (nrow, ncol) set to the of the scalar:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">diag</span>(4)
     [,1] [,2] [,3] [,4]
[1,]    1    0    0    0
[2,]    0    1    0    0
[3,]    0    0    1    0
[4,]    0    0    0    1
</code></pre>
<h4>Matrix from vector</h4>
<p>If you specify <code>x</code> as a <code>vector</code> you will return a <code>matrix</code> where the diagonals are the values in <code>x</code> and the other elements are <code>0</code>:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">diag</span>(x = c(3,4,2,6))
     [,1] [,2] [,3] [,4]
[1,]    3    0    0    0
[2,]    0    4    0    0
[3,]    0    0    2    0
[4,]    0    0    0    6
</code></pre>
<h4>Set diagonals for existing matrix</h4>
<p>You can set the diagonals for an existing <code>matrix</code> by assigning values:</p>
<pre><code class="language-r" lang="r">mm
     [,1] [,2]
[1,]    8    1
[2,]    1    9

<span style="color: #0000ff;">diag</span>(mm) &lt;- 100
mm
     [,1] [,2]
[1,]  100    1
[2,]    1  100

diag(mm) &lt;- c(6,3)
mm
     [,1] [,2]
[1,]    6    1
[2,]    1    3

CC
     [,1] [,2] [,3]
[1,]    3    1   -5
[2,]    2    0    4
[3,]    1    6    3

<span style="color: #0000ff;">diag</span>(CC) &lt;- c(99, 999)
Error in `diag&lt;-`(`*tmp*`, value = c(99, 999)) :
  replacement diagonal has wrong length
</code></pre>
<p><strong>Note</strong>:</p>
<ul>
<li>If you specify a single value it is used for all diagonals.</li>
<li>If you specify the &#8220;correct&#8221; number of elements you replace the existing values.</li>
<li>If you specify too few or too many elements you get an error.</li>
</ul>
<h3 id="eigen">Eigenvalues and eigenvectors</h3>
<p>Spectral decomposition of a <code>matrix</code> produces eigenvalues and eigenvectors. These values are used often in linear algebra and various branches of mathematics.</p>
<p>The <code>R</code> function <code>eigen()</code> can compute the eigenvalues and eigenvectors of a (square) <code>matrix</code>.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">eigen</span>(x, symmetric, only.values = FALSE)
</code></pre>
<p>The <code>eigen()</code> function only works on square <code>matrix</code> objects.</p>
<p>The <code>symmetric</code> parameter allows you to specify <code>TRUE</code> to force the calculations to use only the lower triangle, when you have symmetrical <code>matrix</code> objects. If you leave this to the default then the function checks to see if the values are symmetric.</p>
<p>The <code>only.values</code> parameter can be set to <code>TRUE</code> to return only the eigenvalues.</p>
<pre><code class="language-r" lang="r">m
     [,1] [,2]
[1,]    5    1
[2,]    1    3

<span style="color: #0000ff;">eigen</span>(m)
eigen() decomposition
$values
[1] 5.414214 2.585786

$vectors
           [,1]       [,2]
[1,] -0.9238795  0.3826834
[2,] -0.3826834 -0.9238795
</code></pre>
<p>If you have negative values you&#8217;ll return <code>complex</code> values:</p>
<pre><code class="language-r" lang="r">M
     [,1] [,2]
[1,]    5   -2
[2,]    2    4

<span style="color: #0000ff;">eigen</span>(M)
eigen() decomposition
$values
[1] 4.5+1.936492i 4.5-1.936492i

$vectors
                     [,1]                 [,2]
[1,] 0.7071068+0.0000000i 0.7071068+0.0000000i
[2,] 0.1767767-0.6846532i 0.1767767+0.6846532i
</code></pre>
<h3 id="svd">Singular Value Decomposition</h3>
<p>Singular value decomposition of a <code>matrix</code> is important in many statistical routines. SVD is a kind of factorisation of a <code>matrix</code> and is carried out in <code>R</code> with the <code>svd()</code> function:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">svd</span>(x, nu = min(n, p), nv = min(n, p))
</code></pre>
<p>In the <code>svd()</code> function:</p>
<ul>
<li><code>x</code> is a <code>matrix</code></li>
<li><code>nu</code> is the number of left singular vectors to compute</li>
<li><code>nv</code> is the number of right singular vectors to compute</li>
</ul>
<p>The <code>svd()</code> function returns a result with several components:</p>
<ul>
<li><code>$d</code> a <code>vector</code> of singular values in descending order.</li>
<li><code>$u</code> a <code>matrix</code> of left singular vectors.</li>
<li><code>$v</code> a <code>matrix</code> of right singular vectors.</li>
</ul>
<pre><code class="language-r" lang="r">C
     [,1] [,2] [,3]
[1,]    3    1   -5
[2,]    2    0    4
[3,]    1    6    3

<span style="color: #0000ff;">svd</span>(C)
$d
[1] 7.620874 5.810848 3.025941

$u
           [,1]       [,2]       [,3]
[1,] -0.4710376 -0.7804341 -0.4111522
[2,]  0.4517527  0.1869132 -0.8723434
[3,]  0.7576563 -0.5966457  0.2645201

$v
           [,1]       [,2]       [,3]
[1,] 0.03254861 -0.4412646 -0.8967866
[2,] 0.53470246 -0.7503738  0.3886290
[3,] 0.84441333  0.4921633 -0.2115217
</code></pre>
<p>You can use the <code>nu</code> and <code>nv</code> arguments to reduce (to <code>0</code> if you like) the number of left and/or right singular vectors.</p>
<pre><code class="language-r" lang="r">VADeaths
      Rural Male Rural Female Urban Male Urban Female
50-54       11.7          8.7       15.4          8.4
55-59       18.1         11.7       24.3         13.6
60-64       26.9         20.3       37.0         19.3
65-69       41.0         30.9       54.6         35.1
70-74       66.0         54.3       71.1         50.0

<span style="color: #0000ff;">svd</span>(VADeaths, nu = 2, nv = 2)
$d
[1] 161.967972  10.037542   3.212076   1.194284

$u
           [,1]       [,2]
[1,] -0.1404491 -0.1476512
[2,] -0.2161352 -0.3623160
[3,] -0.3297674 -0.4373676
[4,] -0.5099065 -0.4819224
[5,] -0.7515374  0.6506817

$v
           [,1]       [,2]
[1,] -0.5243856  0.3123820
[2,] -0.4137210  0.6015805
[3,] -0.6229108 -0.7282861
[4,] -0.4072306  0.1005871
</code></pre>
<h3 id="chol">Cholesky decomposition</h3>
<p>Compute the Choleski (Cholesky) factorization of a real symmetric positive-definite square <code>matrix</code> using the <code>chol()</code>function. It is a kind of optimisation that can be used in various mathematical problems.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">chol</span>(x, pivot = FALSE, tol = -1, ...)
</code></pre>
<p>In <code>chol()</code>:</p>
<ul>
<li><code>x</code> is a <code>matrix</code>, which should be positive and symmetric, (i.e. square).</li>
<li><code>pivot</code> can be set to <code>TRUE</code> in some cases where the <code>matrix</code> is semi-positive definite.</li>
<li><code>tol</code> is used to set a tolerance when <code>pivot = TRUE</code>.</li>
</ul>
<p>How to tell if a matrix is positive definite, or positive semi-definite?</p>
<ul>
<li>A <code>matrix</code> is <strong>symmetric</strong> if <code>nrow</code> = <code>ncol</code>, in other words, square. In addition the transposed <code>matrix</code> must be the same as the original.</li>
<li>If all the eigenvalues are positive (&gt;0) the <code>matrix</code> is <strong>positive definite</strong>.</li>
<li>If any eigenvalues are <code>0</code> and the others positive then the <code>matrix</code> is <strong>positive semi-definite</strong>.</li>
</ul>
<p>You can check the eigenvalues with <code>eigen(x)</code>.</p>
<pre><code class="language-r" lang="r">m
     [,1] [,2]
[1,]    5    1
[2,]    1    3

<span style="color: #808000;"># Check matrix is positive definite</span>
<span style="color: #0000ff;">eigen</span>(m)$val
[1] 5.414214 2.585786

<span style="color: #808000;"># Check that matrix is symmetric</span>
<span style="color: #0000ff;">identical</span>(m, <span style="color: #0000ff;">t</span>(m))
[1] TRUE

<span style="color: #0000ff;">chol</span>(m)
         [,1]      [,2]
[1,] 2.236068 0.4472136
[2,] 0.000000 1.6733201

A
     [,1] [,2]
[1,]    4   -1
[2,]    1    3

<span style="color: #808000;"># Check matrix (it is complex but is +ve definite)</span>
<span style="color: #0000ff;">eigen</span>(A)$val
[1] 3.5+0.866025i 3.5-0.866025i

# Check if matrix is symmetric
<span style="color: #0000ff;">identical</span>(A, <span style="color: #0000ff;">t</span>(A))
[1] FALSE

<span style="color: #808000;"># chol() will return a result as it does not check symmetry!
</span></code></pre>
<p>If you have an eigenvalue of <code>0</code> (with the others <code>&gt;0</code>) then your <code>matrix</code> is positive semi-definite. You can perform Cholensky decomposition with <code>chol()</code> but need to use <code>pivot = TRUE</code> as an argument.</p>
<pre><code class="language-r" lang="r">im &lt;- <span style="color: #0000ff;">matrix</span>(c(1,-1, -1,1), ncol = 2)

im
     [,1] [,2]
[1,]    1   -1
[2,]   -1    1

<span style="color: #808000;"># matrix is +ve semi-definite</span>
eigen(im)$val
[1] 2 0

<span style="color: #808000;"># Check symmetric</span>
<span style="color: #0000ff;">identical</span>(im, <span style="color: #0000ff;">t</span>(im))
[1] TRUE

<span style="color: #0000ff;">chol</span>(im)
Error in chol.default(im) :
  the leading minor of order 2 is not positive definite

<span style="color: #808000;"># Need to use pivot = TRUE</span>
<span style="color: #0000ff;">chol</span>(im, pivot = TRUE)
     [,1] [,2]
[1,]    1   -1
[2,]    0    0
attr(,"pivot")
[1] 1 2
attr(,"rank")
[1] 1
Warning message:
In chol.default(im, pivot = TRUE) :
  the matrix is either rank-deficient or indefinite
</code></pre>
<p>Note that you still get a warning!</p>
<p>The eigenvalues need to be <code>&gt;0</code> but there is a tolerance:</p>
<pre><code class="language-r" lang="r">mat &lt;- <span style="color: #0000ff;">matrix</span>(c(4,12,-16, 12,37,-43, -16,-43,98), ncol = 3)
mat
     [,1] [,2] [,3]
[1,]    4   12  -16
[2,]   12   37  -43
[3,]  -16  -43   98

<span style="color: #808000;"># Eigenvalues all &gt;0 (just)</span>
<span style="color: #0000ff;">eigen</span>(mat)$val
[1] 123.47723179  15.50396323   0.01880498

<span style="color: #808000;"># Check symmetry</span>
<span style="color: #0000ff;">identical</span>(mat, <span style="color: #0000ff;">t</span>(mat))
[1] TRUE

<span style="color: #0000ff;">chol</span>(mat)
     [,1] [,2] [,3]
[1,]    2    6   -8
[2,]    0    1    5
[3,]    0    0    3

a &lt;- <span style="color: #0000ff;">matrix</span>(c(2,3,1,11, 3,9,3,30, 1,3,1,10, 11,30,10,101))
a
     [,1] [,2] [,3] [,4]
[1,]    2    3    1   11
[2,]    3    9    3   30
[3,]    1    3    1   10
[4,]   11   30   10  101

<span style="color: #808000;"># Very small eigenvalue registers as effectively 0</span>
eigen(a)$val
[1] 1.120990e+02 9.009892e-01 1.681988e-14 1.831868e-15

<span style="color: #808000;"># Check symmetry</span>
<span style="color: #0000ff;">identical</span>(a, <span style="color: #0000ff;">t</span>(a))
[1] TRUE

<span style="color: #0000ff;">chol</span>(a)
Error in chol.default(a) :
  the leading minor of order 3 is not positive definite
</code></pre>
<p>If you try to use <code>pivot = TRUE</code> on a <code>matrix</code> that is not positive (i.e. non-negative definite), you&#8217;ll get a result with a warning. However, the result will be meaningless!</p>
<pre><code class="language-r" lang="r"><span style="color: #808000;"># Negative definite i.e. not non-negative definite</span>
b &lt;- <span style="color: #0000ff;">matrix</span>(c(5,-5,-5,3), 2, 2)
b
     [,1] [,2]
[1,]    5   -5
[2,]   -5    3

<span style="color: #808000;"># check symmetry -- okay</span>
<span style="color: #0000ff;">identical</span>(b, <span style="color: #0000ff;">t</span>(b))
[1] TRUE

<span style="color: #808000;"># negative eigenvalues, so no +ve</span>
<span style="color: #0000ff;">eigen</span>(b)$val
[1]  9.09902 -1.09902

<span style="color: #808000;"># pivot = TRUE runs but result is meaningless!
#.. not shown
</span></code></pre>
<h3 id="qr">QR Decomposition</h3>
<p>QR decomposition is used in many statistical methods, especially in regression. The <code>qr()</code> function carries out the calculations.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">qr</span>(x, tol = 1e-07 , LAPACK = FALSE, ...)
</code></pre>
<p>In <code>qr()</code>:</p>
<ul>
<li><code>x</code> is a <code>matrix</code> to be decomposed.</li>
<li><code>tol</code> is a tolerance used for detecting linear dependencies (you probably won&#8217;t need to tinker with this).</li>
<li><code>LAPACK</code> is which QR algorithm to use, the default uses <code>LINPACK</code>.</li>
</ul>
<p>The result of <code>qr()</code> is an object with various components:</p>
<pre><code class="language-r" lang="r">C
     [,1] [,2] [,3]
[1,]    3    1   -5
[2,]    2    0    4
[3,]    1    6    3

<span style="color: #0000ff;">qr</span>(C)
$qr
           [,1]      [,2]     [,3]
[1,] -3.7416574 -2.405351 1.069045
[2,]  0.5345225  5.586975 2.787095
[3,]  0.2672612 -0.983516 6.410089

$rank
[1] 3

$qraux
[1] 1.801784 1.180821 6.410089

$pivot
[1] 1 2 3

attr(,"class")
[1] "qr"
</code></pre>
<p>QR decomposition is a potentially large topic, which there is not space for here! In addition to the <code>qr()</code> function there are various <em>helper</em> functions. See the help entry in <code>qr()</code> for more information about those.</p>
<h3 id="det">Determinant</h3>
<p>You can calculate the of a square <code>matrix</code> using the <code>det()</code> function. A square <code>matrix</code> is one where <code>nrow</code> = <code>ncol</code> but it doesn&#8217;t have to be symmetrical (where <code>x = t(x)</code>).</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">det</span>(x)
<span style="color: #0000ff;">determinant</span>(x, logarithm = TRUE)
</code></pre>
<p>The <code>det()</code> function returns the determinant. The <code>determinant()</code> function returns the modulus of the determinant and the sign. The default for <code>determinant()</code> is to return the <code>log</code> of the determinant.</p>
<pre><code class="language-r" lang="r">A
     [,1] [,2]
[1,]    4   -1
[2,]    1    3

<span style="color: #808000;"># Matrix is square but no matter that it is not symmetric</span>
<span style="color: #0000ff;">identical</span>(A, <span style="color: #0000ff;">t</span>(A))
[1] FALSE

<span style="color: #0000ff;">det</span>(A)
[1] 13

<span style="color: #0000ff;">determinant</span>(A)
$modulus
[1] 2.564949
attr(,"logarithm")
[1] TRUE

$sign
[1] 1

attr(,"class")
[1] "det"

<span style="color: #0000ff;">determinant</span>(A, logarithm = FALSE)
$modulus
[1] 13
attr(,"logarithm")
[1] FALSE

$sign
[1] 1

attr(,"class")
[1] "det"
</code></pre>
<p>Note that the <code>logarithm</code> argument <strong>cannot</strong> be abbreviated.</p>
<h3 id="cross">Cross-products</h3>
<p>Cross products are where you multiply two <code>matrix</code> objects (inner product), but one is transposed. The <code>R</code> functions <code>crossprod()</code> and <code>tcrossprod()</code> can carry out the calculations.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">crossprod</span>(x, y = NULL)
<span style="color: #0000ff;">tcrossprod</span>(x, y = NULL)
</code></pre>
<p>You specify at least one <code>matrix</code> object <code>x</code>. Object <code>y</code> is optional, if not specified <code>x</code> is used. These functions are essentially equivalent to:</p>
<ul>
<li><code>t(x) %*% y</code> for <code>crossprod()</code></li>
<li><code>x %*% t(y)</code> for <code>tcrossprod()</code></li>
</ul>
<pre><code class="language-r" lang="r">b
     [,1] [,2]
[1,]    5   -5
[2,]   -5    3

<span style="color: #0000ff;">crossprod</span>(b)
     [,1] [,2]
[1,]   50  -40
[2,]  -40   34

B
     [,1] [,2]
[1,]    1    3
[2,]   -2   -4
[3,]    2    0

D
     [,1]
[1,]    3
[2,]    2
[3,]   -2

<span style="color: #0000ff;">crossprod</span>(B, D)
     [,1]
[1,]   -5
[2,]    1
</code></pre>
<p>You get an error if the dimensions are &#8220;wrong&#8221;:</p>
<pre><code class="language-r" lang="r">A
     [,1] [,2]
[1,]    4   -1
[2,]    1    3

D
     [,1]
[1,]    3
[2,]    2
[3,]   -2

<span style="color: #0000ff;">crossprod</span>(A, D)
Error in crossprod(A, D) : non-conformable arguments
</code></pre>
<p>If you specify a <code>vector</code> it will be &#8220;converted&#8221; to a one-column or one-row <code>matrix</code>:</p>
<pre><code class="language-r" lang="r">tcrossprod(1:4)
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    2    4    6    8
[3,]    3    6    9   12
[4,]    4    8   12   16
</code></pre>
<h2 id="misc-tools">Miscellaneous tools</h2>
<p>There are various other tools that you can use with <code>matrix</code> objects:</p>
<h3 id="transpose">Transposition</h3>
<p>Perhaps the simplest <code>matrix</code> operation is to transpose, that is switch the rows and columns. You can carry out <code>matrix</code>transposition using the <code>t()</code> function.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">t</span>(x)
</code></pre>
<p>Example: transpose matrix objects</p>
<pre><code class="language-r" lang="r">x
     [,1] [,2] [,3]
[1,]    1    3    1
[2,]    1    0    0

<span style="color: #0000ff;">t</span>(x)
     [,1] [,2]
[1,]    1    1
[2,]    3    0
[3,]    1    0

D
     [,1]
[1,]    3
[2,]    2
[3,]   -2

<span style="color: #0000ff;">t</span>(D)
     [,1] [,2] [,3]
[1,]    3    2   -2
</code></pre>
<h3 id="triangles">Upper and Lower triangles</h3>
<p>You can &#8220;see&#8221; the upper or lower triangles of a <code>matrix</code> (or any 2-D object) using <code>upper.tri()</code> and <code>lower.tri()</code>functions. These give you a <code>logical</code> <code>matrix</code> the same size as the original, i.e. <code>TRUE</code> or <code>FALSE</code> values.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">upper.tri</span>(x, diag = FALSE)
<span style="color: #0000ff;">lower.tri</span>(x, diag = FALSE)
</code></pre>
<p>You can optionally set <code>diag = TRUE</code> to return the diagonals as <code>TRUE</code>.</p>
<pre><code class="language-r" lang="r">A
     [,1] [,2]
[1,]    4   -1
[2,]    1    3

<span style="color: #0000ff;">upper.tri</span>(A)
      [,1]  [,2]
[1,] FALSE  TRUE
[2,] FALSE FALSE

B
     [,1] [,2]
[1,]    1    3
[2,]   -2   -4
[3,]    2    0

<span style="color: #0000ff;">lower.tri</span>(B, diag = TRUE)
     [,1]  [,2]
[1,] TRUE FALSE
[2,] TRUE  TRUE
[3,] TRUE  TRUE
</code></pre>
<h3 id="row-index">Row and Column index</h3>
<p>You can produce a <code>matrix</code> of <code>integer</code> values based on their position in a <code>matrix</code> object (or similar 2-D object). The <code>row()</code> and <code>col()</code> functions operate over rows and columns respectively.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">row</span>(x, as.factor = FALSE)
<span style="color: #0000ff;">.row</span>(dim)

<span style="color: #0000ff;">col</span>(x, as.factor = FALSE)
<span style="color: #0000ff;">.col</span>(dim)
</code></pre>
<p>Essentially you provide a <em>template</em> object and the functions return a new object with the appropriate values.</p>
<pre><code class="language-r" lang="r">C
     [,1] [,2] [,3]
[1,]    3    1   -5
[2,]    2    0    4
[3,]    1    6    3

<span style="color: #0000ff;">row</span>(C)
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3
</code></pre>
<p>If you specify the argument <code>as.factor</code> you can get the result stored as a <code>factor</code> rather than a regular <code>numeric</code>.</p>
<pre><code class="language-r" lang="r">E
     [,1] [,2] [,3]
[1,]   -3    2    0
[2,]    0    5   -1

<span style="color: #0000ff;">col</span>(E, as.factor = TRUE)
     [,1] [,2] [,3]
[1,] 1    2    3
[2,] 1    2    3
Levels: 1 2 3
</code></pre>
<p>There are alternative versions <code>.row()</code> and <code>.col()</code>, which take a <code>vector</code> argument, giving the dimensions of the <code>matrix</code>for which the indices are required.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">.row</span>(dim = c(3, 5))
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
</code></pre>
<hr />
<h2>Summary</h2>
<p>The topic of <code>matrix</code> math is extensive! This article is not intended to be an exhaustive thesis on the subject but more of an introduction to some of the <code>R</code> tools that you can use to carry out <code>matrix</code> math, and other operations.</p>
<hr />
<p>This article is partly in support of my book <em>An Introduction to R</em> see the <a href="https://www.dataanalytics.org.uk/publications">publications page</a> for more information.</p>
<p>An Introduction to R will be published by <a href="https://pelagicpublishing.com/">Pelagic Publishing</a>. <a href="https://pelagicpublishing.com/pages/search-results-page?q=Mark%20Gardener">See all my books at Pelagic Publishing</a>.</p>
<p>For more articles visit the <a href="https://www.dataanalytics.org.uk/category/tips-and-tricks/">Tips and Tricks page</a> and look for the various categories or use the search box.</p>
<p>See also the <a>Knowledge Base</a> where there are other topics related to R and data science.</p>
<p>Look at our other books on the <a>Publications Page</a>.</p>
<p>Visit our other site at <a href="https://www.gardenersown.co.uk/">GardenersOwn</a> for a more ecological matters.</p>
<p>The post <a href="https://dataanalytics.org.uk/matrix-math-operations-using-r/">Matrix Math</a> appeared first on <a href="https://dataanalytics.org.uk">Data Analytics</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Association Plots in R</title>
		<link>https://dataanalytics.org.uk/association-plots-in-r/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=association-plots-in-r</link>
		
		<dc:creator><![CDATA[gmark]]></dc:creator>
		<pubDate>Thu, 28 Jul 2022 15:43:52 +0000</pubDate>
				<category><![CDATA[Introduction-to-R]]></category>
		<category><![CDATA[association]]></category>
		<category><![CDATA[association plot]]></category>
		<category><![CDATA[assocplot]]></category>
		<category><![CDATA[chi squared]]></category>
		<category><![CDATA[data visualisation]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[plot]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[visualisation]]></category>
		<category><![CDATA[visualization]]></category>
		<guid isPermaLink="false">https://www.dataanalytics.org.uk/?p=39538</guid>

					<description><![CDATA[<p>Association Plots Association plots in R. An association plot draws the results of an association test by charting the Pearson Residuals. Association plots in [&#8230;]</p>
<p>The post <a href="https://dataanalytics.org.uk/association-plots-in-r/">Association Plots in R</a> appeared first on <a href="https://dataanalytics.org.uk">Data Analytics</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1>Association Plots</h1>
<p>Association plots in R. An association plot draws the results of an association test by charting the Pearson Residuals.</p>
<p>Association plots in R are drawn using <code>assocplot()</code></p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">assocplot</span>(x, col = c("black", "red"), space = 0.3,
          main = NULL, xlab = NULL, ylab = NULL)
</code></pre>
<figure>
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Explanation</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>x</code></td>
<td>the data, usually a <code>numeric</code> <code>matrix</code>.</td>
</tr>
<tr>
<td><code>col</code></td>
<td>colors for positive and negative associations.</td>
</tr>
<tr>
<td><code>space</code></td>
<td>amount of space between the bars, as a fraction of average bar height and width (default = <code>0.3</code>).</td>
</tr>
<tr>
<td><code>main</code>, <code>xlab</code>, <code>ylab</code></td>
<td>title annotations.</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>Essentially you need a 2-dimensional <code>matrix</code> to use <code>assocplot()</code>:</figure>
<pre><code class="language-r" lang="r">VADeaths
</code></pre>
<pre><code>      Rural Male Rural Female Urban Male Urban Female
50-54       11.7          8.7       15.4          8.4
55-59       18.1         11.7       24.3         13.6
60-64       26.9         20.3       37.0         19.3
65-69       41.0         30.9       54.6         35.1
70-74       66.0         54.3       71.1         50.0
</code></pre>
<p>Apart from the titles, the only graphical parameter you can alter directly is <code>col</code>, to alter the positive and negative bar colors:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">assocplot</span>(VADeaths, col = c(<span style="color: #008000;">"lightblue"</span>, <span style="color: #008000;">"pink"</span>),
	  xlab = <span style="color: #008000;">"Age class"</span>, ylab = <span style="color: #008000;">"Driver actegory"</span>)
</code></pre>
<div id="attachment_39537" style="width: 510px" class="wp-caption aligncenter"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-39537" class="wp-image-39537" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-warp-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-warp-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-warp-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-warp-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-warp-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-warp-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-warp.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39537" class="wp-caption-text">Basic association plot using custom color for positive and negative bars</p></div>
<h2>Graphical parameters</h2>
<p>If you want to alter the general appearance of your association plot you&#8217;ll need to set the appropriate graphical parameters using <code>par()</code> before using <code>assocplot()</code>:</p>
<pre><code class="language-r" lang="r">opar &lt;- <span style="color: #0000ff;">par</span>(las = 1, cex = 0.8, mar = c(5,7,2,1))

<span style="color: #0000ff;">assocplot</span>(VADeaths, col = c(<span style="color: #008000;">"blue"</span>, <span style="color: #008000;">"tomato"</span>),
          space = 0.05, xlab = <span style="color: #008000;">"Age class"</span>)
<span style="color: #0000ff;">title</span>(ylab = <span style="color: #008000;">"Driver category"</span>, line = 6)

<span style="color: #0000ff;">par</span>(opar)
</code></pre>
<div id="attachment_39536" style="width: 510px" class="wp-caption aligncenter"><img decoding="async" aria-describedby="caption-attachment-39536" class="wp-image-39536" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-par-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-par-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-par-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-par-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-par-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-par-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-par.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39536" class="wp-caption-text">Custom graphical parameters have to be applied using par() before using assocplot()</p></div>
<p>In the preceding example the margins were widened to allow the labels to &#8220;fit&#8221;. Note also how <code>title()</code> was used to place the y-axis annotation on an outer line.</p>
<h2>Data layout</h2>
<p>Essentially you need a 2D <code>matrix</code> for <code>assocplot()</code> to make an association plot in R. If you have something else you need to coerce it to the correct form.</p>
<p>Here are some options:</p>
<ul>
<li><code>data.frame</code> use <code>as.matrix()</code> to alter the form.</li>
<li><code>table</code> use <code>x[r, c, n, ...]</code> to &#8220;pick out&#8221; the appropriate 2D sub-table or..</li>
<li><code>table</code> use <code>margin.table</code> to &#8220;collapse&#8221; a table and combine across the margins you want.</li>
</ul>
<pre><code class="language-r" lang="r"><span style="color: #808080;"># 3D table</span>
HairEyeColor
</code></pre>
<pre><code>, , Sex = Male

       Eye
Hair    Brown Blue Hazel Green
  Black    32   11    10     3
  Brown    53   50    25    15
  Red      10   10     7     7
  Blond     3   30     5     8

, , Sex = Female

       Eye
Hair    Brown Blue Hazel Green
  Black    36    9     5     2
  Brown    66   34    29    14
  Red      16    7     7     7
  Blond     4   64     5     8
</code></pre>
<pre><code class="language-r" lang="r"><span style="color: #808080;"># Choose "Male"</span>
HairEyeColor[,,1]
</code></pre>
<pre><code>       Eye
Hair    Brown Blue Hazel Green
  Black    32   11    10     3
  Brown    53   50    25    15
  Red      10   10     7     7
  Blond     3   30     5     8
</code></pre>
<pre><code class="language-r" lang="r"><span style="color: #808080;"># Combine "Male" and "Female"</span>
<span style="color: #0000ff;">margin.table</span>(HairEyeColor, margin = c(1,2))
</code></pre>
<pre><code>       Eye
Hair    Brown Blue Hazel Green
  Black    68   20    15     5
  Brown   119   84    54    29
  Red      26   17    14    14
  Blond     7   94    10    16
</code></pre>
<pre><code class="language-r" lang="r"><span style="color: #808080;"># Combine "Eye"</span>
<span style="color: #0000ff;">margin.table</span>(HairEyeColor, margin = c(1,3))
</code></pre>
<pre><code>       Sex
Hair    Male Female
  Black   56     52
  Brown  143    143
  Red     34     37
  Blond   46     81
</code></pre>
<h2>Alternatives to assocplot()</h2>
<p>The <code>assocplot()</code> function is not the only was to draw an association plot using R. You could run a <code>chisq.test()</code> and extract the Pearson residuals <code>$residuals</code>, which you then plot using <code>barplot()</code>.</p>
<pre><code class="language-r" lang="r">X &lt;- <span style="color: #0000ff;">chisq.test</span>(VADeaths)
X$residuals
</code></pre>
<pre><code>         Rural Male Rural Female Urban Male Urban Female
50-54 -0.0001229145  -0.09956533  0.2454344  -0.21106734
55-59  0.0422284686  -0.56107962  0.4550546  -0.06391943
60-64 -0.0951496863  -0.16808112  0.5368919  -0.40335827
65-69 -0.2718462679  -0.34870589  0.2349807   0.36003546
70-74  0.2624133483   0.73510055 -0.8898149   0.09370444
</code></pre>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">barplot</span>(X$residuals, beside = TRUE, col = <span style="color: #0000ff;">cm.colors</span>(5),
        ylim = c(-1,1), legend = TRUE,
	args.legend = <span style="color: #0000ff;">list</span>(x = "top", bty = "n", ncol = 5))
<span style="color: #0000ff;">title</span>(ylab = "Pearson residuals", xlab = "Category")
</code></pre>
<div id="attachment_39535" style="width: 510px" class="wp-caption aligncenter"><img decoding="async" aria-describedby="caption-attachment-39535" class="wp-image-39535" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-bar-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-bar-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-bar-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-bar-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-bar-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-bar-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/assocplot-bar.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39535" class="wp-caption-text">Alternative to assocplot() is to use barplot() on the Pearson residuals</p></div>
<p>To get multiple rows, with a separate mini-plot for each row you would need to set-up <code>par(mfrow = c(rows, cols))</code>.</p>
<p>There are potential advantages to this method, for example you can add horizontal lines at +/- 2 to show the &#8220;significance band&#8221;. However, it is also somewhat more involved!</p>
<hr />
<p>This article is partly in support of my book <em>An Introduction to R</em> see the <a href="https://www.dataanalytics.org.uk/publications">publications page</a> for more information.</p>
<ul>
<li>An Introduction to R will be published by <a href="https://pelagicpublishing.com/">Pelagic Publishing</a>. <a href="https://pelagicpublishing.com/pages/search-results-page?q=Mark%20Gardener">See all my books at Pelagic Publishing</a>.</li>
<li>For more articles look at the <a href="https://www.dataanalytics.org.uk/category/tips-and-tricks/">Tips and Tricks page</a> and look for the various categories or use the search box.</li>
<li>See also the <a href="#https://www.dataanalytics.org.uk/data-analytics-knowledge-base-tips-tricks-r-excel/">Knowledge Base</a> where there are other topics related to R and data science.</li>
<li>Visit our other site at <a href="https://www.gardenersown.co.uk/">GardenersOwn</a> for a more ecological matters.</li>
</ul>
<p>The post <a href="https://dataanalytics.org.uk/association-plots-in-r/">Association Plots in R</a> appeared first on <a href="https://dataanalytics.org.uk">Data Analytics</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Conditional density plots in R</title>
		<link>https://dataanalytics.org.uk/conditional-density-plots-in-r/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=conditional-density-plots-in-r</link>
		
		<dc:creator><![CDATA[gmark]]></dc:creator>
		<pubDate>Thu, 28 Jul 2022 15:39:09 +0000</pubDate>
				<category><![CDATA[Introduction-to-R]]></category>
		<category><![CDATA[cdplot]]></category>
		<category><![CDATA[data visualisation]]></category>
		<category><![CDATA[density]]></category>
		<category><![CDATA[density plot]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[histogram]]></category>
		<category><![CDATA[plot]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[visualisation]]></category>
		<category><![CDATA[visualization]]></category>
		<guid isPermaLink="false">https://www.dataanalytics.org.uk/?p=39529</guid>

					<description><![CDATA[<p>Conditional density plots Conditional density plots in R &#8212; how to draw a conditional density plot using R. A conditional density plot shows [&#8230;]</p>
<p>The post <a href="https://dataanalytics.org.uk/conditional-density-plots-in-r/">Conditional density plots in R</a> appeared first on <a href="https://dataanalytics.org.uk">Data Analytics</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1>Conditional density plots</h1>
<p>Conditional density plots in R &#8212; how to draw a conditional density plot using R. A conditional density plot shows the density of a sample split into groups.</p>
<p>Use <code>cdplot()</code> to draw a conditional density plot using R.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">cdplot</span>(x, y,
       plot = TRUE, tol.ylab = 0.05, ylevels = NULL,
       bw = "nrd0", n = 512, from = NULL, to = NULL,
       col = NULL, border = 1, main = "", xlab = NULL, ylab = NULL,
       yaxlabels = NULL, xlim = NULL, ylim = c(0, 1), ...)
</code></pre>
<p>There are many potential parameters for <code>cdplot()</code> but the most helpful are:</p>
<figure>
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Explanation</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>x</code>, <code>y</code></td>
<td>the data, specify <code>x</code> and <code>y</code> or use a <code>formula</code>. In any event <code>y</code> should be a <code>factor</code> and <code>x</code> a <code>numeric</code></td>
</tr>
<tr>
<td><code>ylevels</code></td>
<td>the order of the variables to be plotted</td>
</tr>
<tr>
<td><code>yaxlabels</code></td>
<td>labels for axis annotation</td>
</tr>
<tr>
<td><code>bw</code>, <code>n</code>, <code>from</code>, <code>to</code>, <code>...</code></td>
<td>arguments to pass to <code>density</code></td>
</tr>
</tbody>
</table>
</figure>
<p>There are several arguments related to the <code>density()</code> function, which in most cases you&#8217;ll never need to alter.</p>
<p>A basic plot requires a <code>factor</code> variable and a <code>numeric</code>:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">cdplot</span>(tension ~ breaks, data = warpbreaks)
</code></pre>
<div id="attachment_39528" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39528" class="wp-image-39528" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39528" class="wp-caption-text">A conditional density plot</p></div>
<p>You can use the <code>ylevels</code> argument to alter the order of the plotting of a <code>cdplot()</code>:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">cdplot</span>(tension ~ breaks, data = warpbreaks, ylevels = 3:1)
</code></pre>
<div id="attachment_39527" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39527" class="wp-image-39527" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-rev-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-rev-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-rev-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-rev-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-rev-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-rev-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-warp-rev.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39527" class="wp-caption-text">Use the ylevels argument to change the order of a conditional density plot</p></div>
<p>Give customized names to the <code>factor</code> levels via the <code>yaxlabels</code> argument:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">cdplot</span>(group ~ weight, data = PlantGrowth,
       yaxlabels = c("Control", "Treatment-1", "Treatment-2"))
</code></pre>
<div id="attachment_39525" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39525" class="wp-image-39525" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-pg-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-pg-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-pg-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-pg-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-pg-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-pg-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-pg.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39525" class="wp-caption-text">Custom factor labels via yaxlabels argument in cdplot</p></div>
<h2>Altering graphical appearance</h2>
<p>Only some of the general graphical parameters can be changed in <code>cdplot()</code>, as in the following example.</p>
<p>Use graphical parameters <code>col</code> and <code>border</code> to alter the appearance:</p>
<pre><span style="color: #0000ff;">cdplot</span>(spray ~ count, data = InsectSprays,
       col = <span style="color: #0000ff;">cm.colors</span>(6), border = "blue")</pre>
<div id="attachment_39526" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39526" class="wp-image-39526" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-spray-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-spray-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-spray-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-spray-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-spray-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-spray-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-spray.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39526" class="wp-caption-text">Basic graphical parameters col and border used to alter a cdplot</p></div>
<p>If you want to change any other graphical parameters you&#8217;ll need to call <code>par()</code> first:</p>
<pre><code class="language-r" lang="r">opar &lt;- <span style="color: #0000ff;">par</span>(las = 1, cex = 0.8, mar = c(5,7,2,3))

<span style="color: #0000ff;">cdplot</span>(feed ~ weight, data = chickwts, ylab = "")
<span style="color: #0000ff;">title</span>(ylab = "feed", line = 5)

<span style="color: #0000ff;">par</span>(opar)
</code></pre>
<div id="attachment_39524" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39524" class="wp-image-39524" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-chick-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-chick-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-chick-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-chick-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-chick-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-chick-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/cdplot-chick.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39524" class="wp-caption-text">Use par() to set graphical parameters (other than col, border) in a cdplot</p></div>
<p>In the preceding example the margins were altered to allow the annotations to &#8220;fit&#8221;. In the <code>title</code> the annotation was shifted outwards.</p>
<p>This article is partly in support of my book <em>An Introduction to R</em> see the <a href="https://www.dataanalytics.org.uk/publications">publications page</a> for more information.</p>
<ul>
<li>For more articles look at the <a href="https://www.dataanalytics.org.uk/category/tips-and-tricks/">Tips and Tricks page</a> and look for the various categories or use the search box.</li>
<li>See also the <a href="#https://www.dataanalytics.org.uk/data-analytics-knowledge-base-tips-tricks-r-excel/">Knowledge Base</a> where there are other topics related to R and data science.</li>
<li>An Introduction to R will be published by <a href="https://pelagicpublishing.com/">Pelagic Publishing</a>. <a href="https://pelagicpublishing.com/pages/search-results-page?q=Mark%20Gardener">See all my books at Pelagic Publishing</a>.</li>
<li>Visit our other site at <a href="https://www.gardenersown.co.uk/">GardenersOwn</a> for a more ecological matters.</li>
</ul>
<p>The post <a href="https://dataanalytics.org.uk/conditional-density-plots-in-r/">Conditional density plots in R</a> appeared first on <a href="https://dataanalytics.org.uk">Data Analytics</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Spine plots using R</title>
		<link>https://dataanalytics.org.uk/spine-plots-using-r/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=spine-plots-using-r</link>
		
		<dc:creator><![CDATA[gmark]]></dc:creator>
		<pubDate>Thu, 28 Jul 2022 09:50:31 +0000</pubDate>
				<category><![CDATA[Introduction-to-R]]></category>
		<category><![CDATA[data visualisation]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[plot]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[spine plot]]></category>
		<category><![CDATA[spineplot]]></category>
		<category><![CDATA[spinogram]]></category>
		<category><![CDATA[visualisation]]></category>
		<category><![CDATA[visualization]]></category>
		<guid isPermaLink="false">https://www.dataanalytics.org.uk/?p=39519</guid>

					<description><![CDATA[<p>Spine Plots using R A spine plot is similar to a mosaic plot and stacked bar chart. Use spineplot()  function to draw spine [&#8230;]</p>
<p>The post <a href="https://dataanalytics.org.uk/spine-plots-using-r/">Spine plots using R</a> appeared first on <a href="https://dataanalytics.org.uk">Data Analytics</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1>Spine Plots using R</h1>
<p>A spine plot is similar to a mosaic plot and stacked bar chart. Use <code>spineplot()</code>  function to draw spine plots using R. There are quite a number of potential arguments you can use:</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">spineplot</span>(x, y = NULL,
          breaks = NULL, tol.ylab = 0.05, off = NULL,
          ylevels = NULL, col = NULL,
          main = "", xlab = NULL, ylab = NULL,
          xaxlabels = NULL, yaxlabels = NULL,
          xlim = NULL, ylim = c(0, 1), axes = TRUE, ...)
</code></pre>
<p>The major parameters are:</p>
<figure>
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>x</code></td>
<td>data (x,y) or formula <code>y~x</code></td>
</tr>
<tr>
<td><code>breaks</code></td>
<td>passed to <code>hist()</code></td>
</tr>
<tr>
<td><code>off</code></td>
<td>space between bars</td>
</tr>
<tr>
<td><code>ylevels</code></td>
<td>order of levels in <code>x</code></td>
</tr>
<tr>
<td><code>col</code></td>
<td>colors</td>
</tr>
<tr>
<td><code>xaxlabels</code></td>
<td>labels for x-axis</td>
</tr>
</tbody>
</table>
</figure>
<p>Your data might be in one of two forms, which affects the kind of plot you get:</p>
<ul>
<li><code>category ~ category</code> results in a spine plot (like a 100% stacked bar chart).</li>
<li><code>factor ~ numeric</code> results in a spinogram (like a histogram).</li>
</ul>
<h2>Spine plots</h2>
<p>If your data are <code>category ~ category</code> your <code>spineplot</code> results in a kind of stacked bar chart.</p>
<p>Look at the <code>VADeaths</code> dataset (a <code>matrix</code>) as an example:</p>
<pre><code class="language-r" lang="r">VADeaths
</code></pre>
<pre><code>      Rural Male Rural Female Urban Male Urban Female
50-54       11.7          8.7       15.4          8.4
55-59       18.1         11.7       24.3         13.6
60-64       26.9         20.3       37.0         19.3
65-69       41.0         30.9       54.6         35.1
70-74       66.0         54.3       71.1         50.0
</code></pre>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">spineplot</span>(VADeaths)
</code></pre>
<div id="attachment_39517" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39517" class="wp-image-39517" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39517" class="wp-caption-text">A simple spine plot from a categorical matrix</p></div>
<p>You can tinker with the graphical parameters to make the chart look &#8220;nicer&#8221;:</p>
<pre><code class="language-r" lang="r"># Custom colours, bar space, and axis labels
<span style="color: #0000ff;">spineplot</span>(VADeaths, col = terrain.colors(4),
          off = 5,
          xlab = "Age Class",
          ylab = "Category")
</code></pre>
<div id="attachment_39516" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39516" class="wp-image-39516" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-col-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-col-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-col-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-col-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-col-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-col-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-vad-col.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39516" class="wp-caption-text">Graphical parameters used to prettify a spine plot</p></div>
<p>It is hard to resize name labels, as <code>cex</code>, <code>las</code> and so on do not work! The solution is to set these parameters globally using <code>par()</code> and reset them after drawing your plot.</p>
<p>In the following example custom <code>names</code> are also used to help &#8220;fit&#8221; labels in the plot:</p>
<pre><code class="language-r" lang="r">opar &lt;- <span style="color: #0000ff;">par</span>(cex.axis = 0.6, las = 2)
<span style="color: #0000ff;">spineplot</span>(USPersonalExpenditure,
          xlab = "", ylab = "",
          xaxlabels = c("FT", "HO", "MH", "PC", "PE"))
<span style="color: #0000ff;">par</span>(opar)
</code></pre>
<div id="attachment_39515" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39515" class="wp-image-39515" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/spine-uspe-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-uspe-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-uspe-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-uspe-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-uspe-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-uspe-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-uspe.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39515" class="wp-caption-text">Axis labels are set using par() before drawing a spineplot</p></div>
<h3>Multi-dimensional tables</h3>
<p>The <code>spineplot()</code> function can only deal with 2-dimensional objects. If you have a multi-dimensional <code>table</code> you need to collapse the table to 2D.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">spineplot</span>(HairEyeColor)
</code></pre>
<pre><code>Error in spineplot.default(HairEyeColor) :
  a 2-way table has to be specified
</code></pre>
<pre><code class="language-r" lang="r">x &lt;- <span style="color: #0000ff;">margin.table</span>(HairEyeColor, margin = c(1,2))
x
</code></pre>
<pre><code>       Eye
Hair    Brown Blue Hazel Green
  Black    68   20    15     5
  Brown   119   84    54    29
  Red      26   17    14    14
  Blond     7   94    10    16
</code></pre>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">spineplot</span>(x, col = c("brown", "blue", "tan", "green"))
</code></pre>
<div id="attachment_39514" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39514" class="wp-image-39514" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/spine-table-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-table-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-table-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-table-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-table-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-table-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-table.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39514" class="wp-caption-text">A multi-dimensional table needs to be collapsed to 2D for plotting</p></div>
<h2>Spinograms</h2>
<p>A spinogram is a <code>spineplot</code> where the data is in the form <code>factor ~ numeric</code>. A spinogram is analogous to a histogram.</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">spineplot</span>(tension ~ breaks, data = warpbreaks)
</code></pre>
<div id="attachment_39518" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39518" class="wp-image-39518" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/spine-warp-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-warp-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-warp-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-warp-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-warp-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-warp-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-warp.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39518" class="wp-caption-text">A spinogram is a form of histogram</p></div>
<p>If you have <code>numeric</code> data you can use <code>factor()</code> to convert the data:</p>
<pre><code class="language-r" lang="r"># Use factor(x) to "convert" numeric
<span style="color: #0000ff;">spineplot</span>(<span style="color: #0000ff;">factor</span>(Month) ~ Ozone,
          data = airquality,
          col = <span style="color: #0000ff;">heat.colors</span>(5))
</code></pre>
<div id="attachment_39512" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39512" class="wp-image-39512" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/spine-air-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-air-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-air-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-air-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-air-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-air-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-air.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39512" class="wp-caption-text">A spinogram where numeric data are converted to a factor before plotting</p></div>
<p>caption: : A spinogram where numeric data are converted to a factor before plotting</p>
<p>Use the <code>breaks</code> argument as you would for <code>hist()</code> to change the breakpoints (you can enter a single <code>integer</code> or a <code>numeric vector</code>).</p>
<pre><code class="language-r" lang="r"><span style="color: #0000ff;">spineplot</span>(feed ~ weight, data = chickwts, breaks = 4)
</code></pre>
<div id="attachment_39513" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39513" class="wp-image-39513" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/spine-chick-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-chick-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-chick-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-chick-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-chick-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-chick-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/spine-chick.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39513" class="wp-caption-text">Using the breaks argument to alter the breakpoints in a spinogram</p></div>
<p>It can be tricky to read a spinogram and it is not trivial to add a legend for the colors. See <a href="https://www.dataanalytics.org.uk/legends-on-graphs-and-charts/">Tips and Tricks article about legends here</a>.</p>
<ul>
<li>This article is partly in support of my book <em>An Introduction to R</em> see the <a href="https://www.dataanalytics.org.uk/publications">publications page</a> for more information.</li>
<li>An Introduction to R will be published by <a href="https://pelagicpublishing.com/">Pelagic Publishing</a>. <a href="https://pelagicpublishing.com/pages/search-results-page?q=Mark%20Gardener">See all my books at Pelagic Publishing</a>.</li>
<li>For more articles visit the <a href="https://www.dataanalytics.org.uk/category/tips-and-tricks/">Tips and Tricks page</a> and look for the various categories or use the search box.</li>
<li>Visit our other site at <a href="https://www.gardenersown.co.uk/">GardenersOwn</a> for a more ecological matters.</li>
</ul>
<hr />
<p>This article is partly in support of my book <em>An Introduction to R</em> see the <a href="https://www.dataanalytics.org.uk/publications">publications page</a> for more information.</p>
<p>The post <a href="https://dataanalytics.org.uk/spine-plots-using-r/">Spine plots using R</a> appeared first on <a href="https://dataanalytics.org.uk">Data Analytics</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Drawing mathematical curves</title>
		<link>https://dataanalytics.org.uk/drawing-mathematical-curves/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=drawing-mathematical-curves</link>
		
		<dc:creator><![CDATA[gmark]]></dc:creator>
		<pubDate>Thu, 28 Jul 2022 09:48:42 +0000</pubDate>
				<category><![CDATA[Introduction-to-R]]></category>
		<category><![CDATA[curve]]></category>
		<category><![CDATA[data visualisation]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[math functions]]></category>
		<category><![CDATA[plot]]></category>
		<category><![CDATA[plotting]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[visualisation]]></category>
		<category><![CDATA[visualization]]></category>
		<guid isPermaLink="false">https://www.dataanalytics.org.uk/?p=39424</guid>

					<description><![CDATA[<p>Drawing mathematical curves using R is fairly easy. Here&#8217;s how to plot mathematical functions using R functions curve and plot. The main functions are [&#8230;]</p>
<p>The post <a href="https://dataanalytics.org.uk/drawing-mathematical-curves/">Drawing mathematical curves</a> appeared first on <a href="https://dataanalytics.org.uk">Data Analytics</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Drawing mathematical curves using R is fairly easy. Here&#8217;s how to plot mathematical functions using R functions curve and plot.</p>
<p>The main functions are <code>curve()</code> and <code>plot.function()</code> but you can simply use <code>plot()</code>.</p>
<pre><span style="color: #0000ff;">curve</span>(expr, from = NULL, to = NULL, n = 101, add = FALSE,
     type = "l", xname = "x", xlab = xname, ylab = NULL,
     log = NULL, xlim = NULL, ...)

<span style="color: #0000ff;">plot</span>(x, y = 0, to = 1, from = y, xlim = NULL, ylab = NULL, ...)</pre>
<p>Essentially you use (or make) a <code>function</code> that takes values of <code>x</code> and returns a single value. The arguments are largely self-explanatory but:</p>
<ul>
<li><code>expr</code>, <code>x</code> &#8212; an expression or <code>function</code> that returns a single result.</li>
<li><code>from</code>, <code>to</code> &#8212; the limits of the input (default <code>0</code>&#8211;<code>1</code>).</li>
<li><code>n</code> &#8212; the number of &#8220;points&#8221; to draw (these will be evenly spaced between <code>from</code> and <code>to</code>).</li>
<li><code>...</code> &#8212; regular graphical arguments can be used.</li>
</ul>
<h2>Simple Math and Trigonometry</h2>
<p>You can visualize built-in functions. <strong>Note</strong> that you can use regular graphics arguments to augment the basic plot.</p>
<p>Here is a plot of the <code>sqrt</code> function:</p>
<pre><span style="color: #0000ff;">curve</span>(sqrt, from = 0, to = 100, ylab = "Square Root", las = 1)</pre>
<div id="attachment_39482" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39482" class="wp-image-39482" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/crv-sqrt.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-sqrt.png 900w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-sqrt-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-sqrt-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-sqrt-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-sqrt-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-sqrt-100x100.png 100w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39482" class="wp-caption-text">Plot of the square root function sqrt()</p></div>
<p>Here is a simple <code>log</code> plot:</p>
<pre><span style="color: #0000ff;">curve</span>(log, from = 0, to = 100, las = 1, lwd = 2, col = "blue")
</pre>
<div id="attachment_39479" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39479" class="wp-image-39479" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/crv-log-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-log-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-log-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-log-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-log-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-log-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-log.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39479" class="wp-caption-text">Plot of log function using curve()</p></div>
<h3>Adding to plots</h3>
<p>Use the <code>add = TRUE</code> argument to add a <code>curve()</code> to an existing plot.</p>
<pre><span style="color: #0000ff;">curve</span>(sin, -pi*2, pi*2, lty = 2, lwd = 1.5, col = "blue",
      ylab = "Function", ylim = c(-1,1.5))

<span style="color: #0000ff;">curve</span>(cos, -pi*2, pi*2, lty = 3, col = "red", lwd = 2, add = TRUE)

<span style="color: #808080;"># Add legend and title</span>
<span style="color: #0000ff;">legend</span>(x = "topright", legend = c("Sine", "Cosine"),
      lty = c(2, 3), lwd = c(1.5, 2),
      col = c("blue", "red"), bty = "n")

<span style="color: #0000ff;">title</span>(main = "Sine and Cosine functions")</pre>
<div id="attachment_39484" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39484" class="wp-image-39484" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/crv-trig-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-trig-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-trig-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-trig-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-trig-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-trig-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-trig.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39484" class="wp-caption-text">Plot of functions sin and cos using curve()</p></div>
<h2>Custom functions</h2>
<p>You can define your own <code>function</code> to plot. <strong>Remember</strong> that the result should be a single value. In this example we define two functions to convert between Celsius and Fahrenheit:</p>
<pre><span style="color: #808080;"># Conversion of temperature</span>
cels &lt;- <span style="color: #0000ff;">function</span>(x) (x-32) * 5/9
fahr &lt;- <span style="color: #0000ff;">function</span>(x) x*9/5 + 32</pre>
<p>Now you can use <code>from</code> and <code>to</code> arguments to set the limits for the input (the default is <code>0</code>&#8211;<code>1</code>).</p>
<pre><span style="color: #0000ff;">curve</span>(cels, from = 32, to = 100, xname = "Farenheit",
      ylab = "Celsius", las = 1)

<span style="color: #0000ff;">curve</span>(fahr, from = 0, to = 50, xname = "Celsius",
      ylab = "Fahrenheit", las = 1)</pre>
<div id="attachment_39483" style="width: 610px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39483" class="wp-image-39483" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/crv-temperature-300x150.png" alt="" width="600" height="300" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-temperature-300x150.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-temperature-1024x512.png 1024w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-temperature-768x384.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-temperature-1536x768.png 1536w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-temperature-600x300.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-temperature.png 1800w" sizes="(max-width: 600px) 100vw, 600px" /><p id="caption-attachment-39483" class="wp-caption-text">Plots using custom function, temperature conversion</p></div>
<h2>Function arguments</h2>
<p>If your function requires additional arguments you need to do something different. In this example you can see the Manning equation, which is used to estimate speed of fluids in pipes/tubes:</p>
<pre>manning &lt;- <span style="color: #0000ff;">function</span>(r, g, c = 0.1) (r^(2/3) * g^0.5/c)

curve(manning) <span style="color: #808080;"># fails</span></pre>
<pre>Error in manning(x) : argument "g" is missing, with no default</pre>
<p>The plotting fails. You need to pre-define all arguments as you cannot &#8220;pass-through&#8221; additional arguments to your function:</p>
<pre>manning &lt;- <span style="color: #0000ff;">function</span>(r, g = 0.01, c = 0.1) (r^(2/3) * g^0.5/c)

<span style="color: #0000ff;">curve</span>(manning) <span style="color: #808080;"># works</span></pre>
<div id="attachment_39480" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39480" class="wp-image-39480" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/crv-manning-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-manning-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-manning-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-manning-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-manning-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-manning-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-manning.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39480" class="wp-caption-text">Plot of a custom function with parameters</p></div>
<p>In the following example you see a built-in <code>function</code> <code>pt()</code> used to visualize the Student&#8217;s t distribution.</p>
<pre><span style="color: #808080;"># pt needs df and lower.tail arguments</span>
PT &lt;- <span style="color: #0000ff;">function</span>(x) pt(q = x, df = 100, lower.tail = FALSE)

<span style="color: #0000ff;">curve</span>(PT, from = -3, to = 3, las = 1, xname = "t-value",
     n = 20, type = "o", pch = 16, ylab = "probability")</pre>
<div id="attachment_39494" style="width: 510px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-39494" class="wp-image-39494" src="https://www.dataanalytics.org.uk/wp-content/uploads/2022/06/crv-pt-300x300.png" alt="" width="500" height="500" srcset="https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-pt-300x300.png 300w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-pt-150x150.png 150w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-pt-768x768.png 768w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-pt-600x600.png 600w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-pt-100x100.png 100w, https://dataanalytics.org.uk/wp-content/uploads/2022/06/crv-pt.png 900w" sizes="(max-width: 500px) 100vw, 500px" /><p id="caption-attachment-39494" class="wp-caption-text">Plot of Student&#8217;s t distribution using a function &#8220;wrapper&#8221;</p></div>
<p>The workaround is to create a &#8220;wrapper&#8221; <code>function</code> that calls the actual <code>function</code> you want with the appropriate arguments. Note that in this example the <code>n</code> argument was used to plot 20 points, along with <code>type</code> and <code>pch</code> to create a line with over-plotted points.</p>
<p>This post is part of the support for the new book <em>An Introduction to R</em>. See <a href="https://www.dataanalytics.org.uk/publications/">Publications home page</a> for more details.</p>
<ul>
<li>An Introduction to R will be published by <a href="https://pelagicpublishing.com/">Pelagic Publishing</a>. <a href="https://pelagicpublishing.com/pages/search-results-page?q=Mark%20Gardener">See all my books at Pelagic Publishing</a>.</li>
<li>For more articles visit the <a href="https://www.dataanalytics.org.uk/category/tips-and-tricks/">Tips and Tricks page</a> and look for the various categories or use the search box.</li>
<li>See also the <a>Knowledge Base</a> where there are other topics related to R and data science.</li>
<li>Look at our other books on the <a>Publications Page</a>.</li>
<li>Visit our other site at <a href="https://www.gardenersown.co.uk/">GardenersOwn</a> for a more ecological matters.</li>
</ul>
<p>The post <a href="https://dataanalytics.org.uk/drawing-mathematical-curves/">Drawing mathematical curves</a> appeared first on <a href="https://dataanalytics.org.uk">Data Analytics</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
