官术网_书友最值得收藏!

Writing a function in R

Most of the tasks in R are performed using functions. A function in R has the same utility as functions in Arithmetic.

Getting ready

In order to write a simple function in R, we must first open a new R script by navigating to File | New file.

How to do it…

We write a very simple function that accepts two values and adds them together. Copy and paste the code in the new blank R script:

add = function (x,y){
  x+y
}

How it works…

A function in R should be defined by function(). Once we define our function, we need to save it as a .r file. Note that the name of the file should be the same as the function; hence we save our function with name add.r.

In order to use the add() function in the R command window, we need to source the file by using the source() function as follows:

source('<your path>/add.R')

Now, we can type add(2,15) in the R command window. You get 17 printed as an output.

The function itself takes two arguments in our recipe but, in reality, it can take many arguments. Anything defined inside curly braces gets executed when we call add(). In our case, we request the user to input two variables, and the output is a simple sum.

See also

  • Functions can be helpful in performing repetitive tasks such as generating plots or perform complicated calculations. Felix Sch?nbrodt has implemented visually weighted watercolor plots in R using a function on his blog at http://www.nicebread.de/visually-weighted-watercolor-plots-new-variants-please-vote/.
  • We can generate similar plots simply by copying the function created by Felix in our R session and executing it. The plotting function created by Felix also provides users with different ways in which the R function's ability could be leveraged to perform repetitive tasks.
主站蜘蛛池模板: 保山市| 广东省| 井冈山市| 淳化县| 五大连池市| 民权县| 咸宁市| 尼玛县| 泗水县| 阿勒泰市| 全椒县| 彰化市| 将乐县| 邻水| 常宁市| 海盐县| 姜堰市| 永宁县| 岳普湖县| 辽宁省| 阳西县| 和硕县| 定边县| 平远县| 慈溪市| 泽库县| 六枝特区| 朔州市| 广南县| 教育| 逊克县| 湘乡市| 吴堡县| 大宁县| 长海县| 民权县| 枝江市| 青海省| 盱眙县| 汪清县| 南投市|