{"id":402,"date":"2020-10-09T08:37:35","date_gmt":"2020-10-09T08:37:35","guid":{"rendered":"http:\/\/thedatapup.com\/home\/?page_id=402"},"modified":"2020-10-09T08:38:18","modified_gmt":"2020-10-09T08:38:18","slug":"r-studio-for-mathematics","status":"publish","type":"page","link":"https:\/\/thedatapup.com\/home\/index.php\/code-tips\/r-studio-for-mathematics\/","title":{"rendered":"R Studio for Mathematics"},"content":{"rendered":"\n<h3>Introduction<\/h3>\n\n\n\n<p>RStudio can be used for a lot of the features that Wolfram Mathematica is often used for, and best of all, RStudio and R are open source and free.<\/p>\n\n\n\n<p>Although I had access to Mathematica during the Maths subject in my Data Science course, I prefer to use software that I can continue to use afterwards, so I came up with ways of using it in place of Wolfram Alpha \/ Mathematica. A lot of it was not very well documented, since it isn\u2019t a common use for it, so hopefully this helps a few others.<\/p>\n\n\n\n<p>NOTE: If you run the code in R-Studio, you can rotate the 3D plots as well<\/p>\n\n\n\n<h2>Differentiation<\/h2>\n\n\n\n<p>Differentiation of (3\/2)x^2 + 5x + 2 + 70\/x<\/p>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># In R-Studio, you may need to go to Tools -> Install Package and choose Deriv\nlibrary(Deriv)\n\n# Set the function and the derivatives\nfx &lt;- expression((3\/2)*x^2 + 5*x + 2 + 70\/x)\ndfx &lt;- Deriv(fx, \"x\")\nddfx &lt;- Deriv(dfx, \"x\")\n\n# Display output\ncat(paste(\"Given f(x) =\", fx), \"\\n\", paste(\"-> f'(x) =\", \n           dfx), \"\\n\", paste(\"-> f''(x) =\", ddfx), \"\\n\")<\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"eclipse\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">## Given f(x) = (3\/2) * x^2 + 5 * x + 2 + 70\/x \n##  -> f'(x) = 3 * x + 5 - 70\/x^2 \n##  -> f''(x) = 140\/x^3 + 3<\/pre>\n<\/div><\/div>\n\n\n\n<h3>Plotting a function<\/h3>\n\n\n\n<p>In this example, we plot the function <strong>f(x) = 2x + 1 + 50\/x<\/strong>, with x axes from <strong>-5 to 5<\/strong> and y axes from <strong>-200 to 200<\/strong>.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># function definition and parameters\nf &lt;- function(x) 2*x + 1 + 50\/x\n\n# Create a function to draw x and y axes with dashed lines\ndraw_axes &lt;- function(){\n  # Draw dashed line for x and y axes \n  abline(h=0, untf=FALSE, col=\"gray\", lwd=1, lty=2)\n  abline(v=0, untf=FALSE, col=\"gray\", lwd=1, lty=2)\n}\n\n# Set the minimum and maximum values for x and y\nxlim &lt;- c(-5, 5)\nylim &lt;- c(-200, 200)\n\n# Draw the curve\ncurve(f, main=\"Your Chart Title\", xlim=xlim, ylim=ylim,\n      xname=\"X Axes Label\", \n      ylab=\"Y Axes Label\", \n      col=\"blue\", # color of the line \n      lwd=2, cex.main=2, cex.lab=1.5);\n# Draw the axes\ndraw_axes()<\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"1024\" height=\"731\" src=\"http:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths1-1024x731.png\" alt=\"\" class=\"wp-image-412\" srcset=\"https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths1-1024x731.png 1024w, https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths1-300x214.png 300w, https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths1-768x549.png 768w, https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths1.png 1344w\" sizes=\"(max-width: 767px) 89vw, (max-width: 1000px) 54vw, (max-width: 1071px) 543px, 580px\" \/><\/figure>\n\n\n\n<h3>Plotting a Relation in 3D<\/h3>\n\n\n\n<p>In this example, we plot the relation <strong>f(x,y) = x^3 + 3<em>x<\/em>y^2 &#8211; 12<em>x + 3<\/em>y^2<\/strong> using the Plotly library.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Use the plotly library to plot our surface\nlibrary(plotly)\n\n# Specify the primary relation as a function called f\nf &lt;- function (x, y) {\n  return (x^3 + 3*x*y^2 - 12*x + 3*y^2)\n}\n\n# Create values of x and y to plot \nx &lt;- seq(-4, 4, by=0.25)\ny &lt;- seq(-3, 3, by=0.25)\n# calculate z based on the relation for each point of (x, y)\nz &lt;- outer(x, y, f)\n\n# This is really important - transpose z, as plotly expects the data in this format\n# I spent many hours trying to figure out what was wrong!!!\nzp &lt;- t(z)\n\n# Use Plotly's surface plot feature\nplot_ly(x = x, y = y, z = zp, type = \"surface\", colorscale='YlOrRd')<\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"672\" height=\"480\" src=\"http:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths2.png\" alt=\"\" class=\"wp-image-414\" srcset=\"https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths2.png 672w, https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths2-300x214.png 300w\" sizes=\"(max-width: 672px) 100vw, 672px\" \/><\/figure>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Note: other available colorscales:  \n#      [\u2018Blackbody\u2019, \u2018Bluered\u2019, \u2018Blues\u2019, \u2018Earth\u2019, \u2018Electric\u2019, \u2018Greens\u2019, \u2018Greys\u2019, \u2018Hot\u2019, \n#       \u2018Jet\u2019, \u2018Picnic\u2019, \u2018Portland\u2019, \u2018Rainbow\u2019,\u2018RdBu\u2019,\u2018Reds\u2019,\u2018Viridis\u2019,\u2018YlGnBu\u2019,\u2018YlOrRd\u2019]<\/pre>\n\n\n\n<h3>Creating a Contour Plot of a Relation<\/h3>\n\n\n\n<p>Here\u2019s a contour plot of the same function above.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Set a color scheme for the contour plot\ncols &lt;- rainbow(60)\n# NOTE: other available colors are: \n#      terrain.colors(25), cm.colors(25) heat.colors(25, alpha=1, rev=FALSE), \n#      rainbow(25), topo.colors(25)\n\n# Draw the contour plot\nfilled.contour(x,y,z, nlevels=25, col=cols, \n               ylab='y', xlab='x',\n               key.title= title('z'))<\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"1024\" height=\"731\" src=\"http:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths3-1024x731.png\" alt=\"\" class=\"wp-image-415\" srcset=\"https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths3-1024x731.png 1024w, https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths3-300x214.png 300w, https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths3-768x549.png 768w, https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths3.png 1344w\" sizes=\"(max-width: 767px) 89vw, (max-width: 1000px) 54vw, (max-width: 1071px) 543px, 580px\" \/><\/figure>\n\n\n\n<h3>Plotting a Relation and Contours in 3D<\/h3>\n\n\n\n<p>Using the same relation, this time projecting contour plots in the 3 dimensional plane..<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">fig &lt;- plot_ly(x=x,y=y,z=zp) %>% add_surface(\n  colorscale = 'YlOrRd', \n  contours = list(\n    z = list(\n      show=TRUE,\n      usecolormap=TRUE,\n      highlightcolor=\"#ff0000\",\n      project=list(z=TRUE), # this projects them onto the plane below\/above\n      # control size of lines between contours, and when they start and end\n      size=50, \n      start=0,\n      end=1500,\n      showlines=TRUE\n      )\n  )\n)\n\nfig<\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"672\" height=\"480\" src=\"http:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths4.png\" alt=\"\" class=\"wp-image-416\" srcset=\"https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths4.png 672w, https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths4-300x214.png 300w\" sizes=\"(max-width: 672px) 100vw, 672px\" \/><\/figure>\n\n\n\n<h3>Bounding a relation with another relation<\/h3>\n\n\n\n<p>Let\u2019s say that we now only want to see the relation <strong>f(x,y) = x^3 + 3<em>x<\/em>y^2 &#8211; 12<em>x + 3<\/em>y^2<\/strong> plotted where the values exist within the boundary of secondary relation.<\/p>\n\n\n\n<p>In this case the secondary relation is an ellipse specified by <strong>x^2 + 3y^2 = 12<\/strong>, so we want to bind everything within <strong>x^2 + 3y^2 &lt;= 12<\/strong>.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Create function of the first relation that only returns values within the\n# bounds of the secondary relation \nfn &lt;- function (x, y) {\n  if ((x^2+3*y^2) &lt;= 12 ) {  # The secondary relation\n    out &lt;- (x^3+3*x*y^2-12*x+3*y^2)   # Return the value from the primary relation\n  } else {\n    out &lt;- \"NULL\"\n  }\n  return (out)\n}\n\n# Generate a dataframe called df,  with two columns x and y, \n# containing an array of combinations of x and y that we used earlier\ndf &lt;- merge(data.frame(x=x), data.frame(y=y))\n\n# Create a column holding the result of the relation on x and y \nvecFn &lt;- Vectorize(fn, vectorize.args = c('x','y'))\n\n# Insert this new column into our dataframe df as column z\ndf$z &lt;- vecFn(df$x, df$y)\n\n# Now drop all values that are the function fn we created marked it as null\n# (ie remove items outside of the bounds)\ndf &lt;- subset(df, z != \"NULL\")\n\n# Convert the z column to numeric (since before it had strings of \"NULL\" in it)\ndf$z &lt;- as.numeric((df$z))\n\n# Finally, plot the dataframe\np &lt;- plot_ly(df, \n             x=~df$x, y=~df$y, z=~df$z, \n             type='mesh3d', intensity=~z, colors=colorRamp(rainbow(5)))\np<\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"672\" height=\"480\" src=\"http:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths5.png\" alt=\"\" class=\"wp-image-417\" srcset=\"https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths5.png 672w, https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths5-300x214.png 300w\" sizes=\"(max-width: 672px) 100vw, 672px\" \/><\/figure>\n\n\n\n<h3>Projecting the bounded relation onto the primary relation<\/h3>\n\n\n\n<p>Lastly, I would like to see how this bounded relation appears on top of the original relation. The result below isn\u2019t perfect, but it gives you an idea.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\" data-enlighter-theme=\"beyond\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># plot the two together using the subplot\nprimary_surface &lt;- plot_ly(x = x, y = y, z = zp, type = \"surface\", colorscale='YlOrRd')\nbounded_surface &lt;- plot_ly(df, x=~df$x, y=~df$y, z=~df$z, \n             type='mesh3d', intensity=~z, colors=colorRamp(rainbow(5)) )\nsubplot(primary_surface, bounded_surface)<\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"507\" height=\"415\" src=\"http:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths6.png\" alt=\"\" class=\"wp-image-413\" srcset=\"https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths6.png 507w, https:\/\/thedatapup.com\/home\/wp-content\/uploads\/2020\/10\/rmaths6-300x246.png 300w\" sizes=\"(max-width: 507px) 100vw, 507px\" \/><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Introduction RStudio can be used for a lot of the features that Wolfram Mathematica is often used for, and best of all, RStudio and R are open source and free. Although I had access to Mathematica during the Maths subject in my Data Science course, I prefer to use software that I can continue to &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/thedatapup.com\/home\/index.php\/code-tips\/r-studio-for-mathematics\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;R Studio for Mathematics&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":212,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":[],"_links":{"self":[{"href":"https:\/\/thedatapup.com\/home\/index.php\/wp-json\/wp\/v2\/pages\/402"}],"collection":[{"href":"https:\/\/thedatapup.com\/home\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/thedatapup.com\/home\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/thedatapup.com\/home\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/thedatapup.com\/home\/index.php\/wp-json\/wp\/v2\/comments?post=402"}],"version-history":[{"count":11,"href":"https:\/\/thedatapup.com\/home\/index.php\/wp-json\/wp\/v2\/pages\/402\/revisions"}],"predecessor-version":[{"id":419,"href":"https:\/\/thedatapup.com\/home\/index.php\/wp-json\/wp\/v2\/pages\/402\/revisions\/419"}],"up":[{"embeddable":true,"href":"https:\/\/thedatapup.com\/home\/index.php\/wp-json\/wp\/v2\/pages\/212"}],"wp:attachment":[{"href":"https:\/\/thedatapup.com\/home\/index.php\/wp-json\/wp\/v2\/media?parent=402"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}