sepideh mashayekhi
sepideh mashayekhi

Reputation: 11

I can't understand what is "function" in R

I'm watching the video for learning R. I'm beginner and , my question is like beginners. but I can't understand what is "function" in R

Upvotes: 1

Views: 66

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269586

A function is something which accepts 0 or more inputs and usually produces an output. It can be thought of as a black box which transforms inputs into an output. For example sqrt is a function which accepts a number (or certain other objects) and returns its square root. Here we run the sqrt function with input 25 and we see it outputs 5.

sqrt(25)
## [1] 5

Typically a function is written as a name followed by parenthesis followed by the input (or inputs separated by commas if there is more than one input) followed by an ending parenthesis as we did above.

There are also infix function such as + which take inputs on either side. For example the + function below inputs 2 and 4 and returns 6

2 + 4
## [1] 6

You can write your own functions. For example this function adds 1 to its argument and returns that.

increment <- function(x) x + 1

# test it out
increment(8)
## [1] 9

R comes with a set of manuals including an Introduction to R which you may wish to review.

Upvotes: 1

Related Questions