{"id":433122,"date":"2018-04-07T22:57:09","date_gmt":"2018-04-07T22:57:09","guid":{"rendered":"https:\/\/essaypaper.org\/writing-your-own-functions-in-r\/"},"modified":"2018-10-24T09:09:24","modified_gmt":"2018-10-24T09:09:24","slug":"writing-your-own-functions-in-r","status":"publish","type":"post","link":"https:\/\/www.benedictsol.com\/blogs\/writing-your-own-functions-in-r\/","title":{"rendered":"Writing your own functions in r"},"content":{"rendered":"<div>\n<div align=\"center\">\n\t\t\t <img decoding=\"async\" src=\"http:\/\/ihelptostudy.com\/other\/custom_top_article.gif\" alt=\"Order custom writing\"\/>\n\t\t<\/div>\n<div class=\"introimage\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/ihelptostudy.com\/wp-content\/uploads\/writing-your-own-functions-in-r_1.png\" width=\"413\" height=\"600\" alt=\"Writing your own functions in r has many built in\" title=\"Writing your own functions in r has many built in\"\/><\/div>\n<p>Abstracting your code into many small functions is key for writing nice R code. In our experience, biologists are initially reluctant to use functions in their code. Where people do use functions, they don\u2019t use them enough, or try to make their functions do too much at once.<\/p>\n<p>R has many built in functions, and you can access many more by installing new packages. So there\u2019s no-doubt you already use functions. This guide will show how to write your own functions, and explain why this is helpful for writing nice R code.<\/p>\n<h2>An example<\/h2>\n<p>Many of the benefits of using functions are more obvious by demonstration than by description. First exhibit is a script that does not use functions. We think that this is typical of the sort of scripts that ecologists end up with when analysing data.<\/p>\n<p>This script can be simplified considerably by using functions, as this script shows.<\/p>\n<p>Note that while we\u2019ve called these \u201cbefore\u201d and \u201cafter\u201d, more typically the process of moving code into functions happens incrementally while writing code.<\/p>\n<h2>Writing your own R functions<\/h2>\n<p>Below we briefly introduce function syntax, and then look at how functions help you to write nice R code. Nice coders with more experience may want to skip the first section.<\/p>\n<p>Writing functions is simple. Paste the following code into your console<\/p>\n<p>You have now created a function called sum.of.squares which requires two arguments and returns the sum of the squares of these arguments. Since you ran the code through the console, the function is now available, like any of the other built-in functions within R. Running sum.of.squares(3,4) will give you the answer 25 .<\/p>\n<div align=\"center\"> <img decoding=\"async\" src=\"http:\/\/ihelptostudy.com\/other\/essay-468.gif\" alt=\"Low cost essay writing\"\/><\/div>\n<p>The procedure for writing any other functions is similar, involving three key steps:<\/p>\n<div class=\"middleimage\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/ihelptostudy.com\/wp-content\/uploads\/writing-your-own-functions-in-r_2.jpg\" width=\"480\" height=\"360\" alt=\"Writing your own functions in r This post looks at\" title=\"Writing your own functions in r This post looks at\"\/><\/div>\n<ol>\n<li>Define the function,<\/li>\n<li>Load the function into the R session,<\/li>\n<li>Use the function.<\/li>\n<\/ol>\n<h3>Defining a function<\/h3>\n<p>Functions are defined by code with a specific format:<\/p>\n<p>function.name. is the function\u2019s name. This can be any valid variable name, but you should avoid using names that are used elsewhere in R, such as dir. function. plot. etc.<\/p>\n<p>arg1, arg2, arg3. these are the arguments of the function, also called formals. You can write a function with any number of arguments. These can be any R object: numbers, strings, arrays, data frames, of even pointers to other functions; anything that is needed for the function.name function to run.<\/p>\n<p>Some arguments have default values specified, such as arg3 in our example. Arguments without a default must have a value supplied for the function to run. You do not need to provide a value for those arguments with a default, as the function will use the default value.<\/p>\n<p>The \u2018\u2026\u2019 argument. The. or ellipsis, element in the function definition allows for other arguments to be passed into the function, and passed onto to another function. This technique is often in plotting, but has uses in many other places.<\/p>\n<p>Function body. The function code between the within the  brackets is run every time the function is called. This code might be very long or very short. Ideally functions are short and do just one thing \u2013 problems are rarely too small to benefit from some abstraction. Sometimes a large function is unavoidable, but usually these can be in turn constructed from a bunch of small functions.<!--image3begin-->\n<\/p>\n<div class=\"3rdimage\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/ihelptostudy.com\/wp-content\/uploads\/writing-your-own-functions-in-r_1.jpg\" width=\"480\" height=\"360\" alt=\"Writing your own functions in r code is that in most\" title=\"Writing your own functions in r code is that in most\"\/><\/div>\n<p><!--image3end--> More on that below.<\/p>\n<p>Return value. The last line of the code is the value that will be returned by the function. It is not necessary that a function return anything, for example a function that makes a plot might not return anything, whereas a function that does a mathematical operation might return a number, or a list.<\/p>\n<h3>Load the function into the R session<\/h3>\n<p>For R to be able to execute your function, it needs first to be read into memory. This is just like loading a library, until you do it the functions contained within it cannot be called.<\/p>\n<p>There are two methods for loading functions into the memory:<\/p>\n<ol>\n<li>Copy the function text and paste it into the console<\/li>\n<li>Use the source() function to load your functions from file.<\/li>\n<\/ol>\n<p>Our recommendation for writing nice R code is that in most cases, you should use the second of these options. Put your functions into a file with an intuitive name, like plotting-fun.R and save this file within the R folder in your project. You can then read the function into memory by calling:<\/p>\n<p>From the point of view of writing nice code, this approach is nice because it leaves you with an uncluttered analysis script, and a repository of useful functions that can be loaded into any analysis script in your project. It also lets you group related functions together easily.<\/p>\n<h3>Using your function<\/h3>\n<p>You can now use the function anywhere in your analysis. In thinking about how you use functions, consider the following:<\/p>\n<ul>\n<li>Functions in R can be treated much like any other R object.<\/li>\n<li>Functions can be passed as arguments to other functions or returned from other functions.<\/li>\n<li>You can define a function inside of another function.<\/li>\n<\/ul>\n<h3>A little more on the ellipsis argument<\/h3>\n<p>The ellipsis argument. is a powerful way of passing an arbitrary number of functions to a lower level function. This is how<\/p>\n<p>and our code would still work.<\/p>\n<h3>Avoiding coding errors<\/h3>\n<p>By using functions, you limit the scope of variables. In the logit function, the p variable is only valid within the body of the logit function \u2013 it is unaffected by any other variable called p and it does not affect any other variable called p. This means when you read code you don\u2019t have to look elsewhere to reason about what values variables might take.<\/p>\n<p>Along similar lines, as much as possible functions should be self contained and not depend on things like global variables (these are variables you\u2019ve defined in the main workspace that would show up in RStudio\u2019s object list).<\/p>\n<h3>Becoming more productive<\/h3>\n<p>Functions enable easy reuse within a project, helping you not to repeat yourself. If you see blocks of similar lines of code through your project, those are usually candidates for being moved into functions.<\/p>\n<p>If your calculations are performed through a series of functions, then the project becomes more modular and easier to change. This is especially the case for which a particular input always gives a particular output.<\/p>\n<h2>How long is a piece of string?<\/h2>\n<p>In our experience, people seem to think that functions are only needed when you need to use a piece of code multiple times, or when you have a really large problem. However, many functions are actually very small. This post looks at the distribution of function length among R packages, and finds that long functions are the exception, rather than the norm.<\/p>\n<h2>Concluding thoughts<\/h2>\n<p>This material written for coders with limited experience. Program design is a bigger topic than could be covered in a whole course, and we haven\u2019t even begun to scratch the surface here. Using functions is just one tool in ensuring that your code will be easy for you to read in future, but it is an essential tool.<\/p>\n<p>The more I write code, the more abstract it gets. And with more abstractions, the apps are easier to maintain. Been working for years&amp;\u2026<\/p>\n<p> Justin Kimbrell (@justin_kimbrell) April 30, 2013<\/p>\n<h2>Further reading<\/h2>\n<p>If you want to read more about function syntax, check out the following:<\/p>\n<p><center><iframe loading=\"lazy\" width=\"420\" height=\"315\" src=\"https:\/\/www.youtube.com\/embed\/S41lXbzSG1E\" frameborder=\"0\" allowfullscreen=\"\"><\/iframe><br \/><\/center><\/p>\n<\/p><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Abstracting your code into many small functions is key for writing nice R code. In our experience, biologists are initially reluctant to use functions in their code. Where people do use functions, they don\u2019t use them enough, or try to <a href=\"https:\/\/www.benedictsol.com\/blogs\/writing-your-own-functions-in-r\/\" class=\"read-more\">Read More &#8230;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,46],"tags":[],"class_list":["post-433122","post","type-post","status-publish","format-standard","hentry","category-uncategorized","category-writing"],"_links":{"self":[{"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/posts\/433122","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/comments?post=433122"}],"version-history":[{"count":0,"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/posts\/433122\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/media?parent=433122"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/categories?post=433122"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.benedictsol.com\/blogs\/wp-json\/wp\/v2\/tags?post=433122"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}