8. Writing R
functions
If we find ourselves running the same code repeatedly, it is probably a good idea to turn it into a function. In programming it is best to reduce redundancy whenever possible. There are several reasons for doing so, including maintainability and ease of reuse. R
has a convenient way to make functions, but it is very different from other languages, so some expectation adjustment might be necessary.
8.1 Hello, World!
This would not be a serious book about a programming language if we did not include a “Hello, World!” example, so we will start with that. Let’s build a function that simply prints “Hello, World!” to the console.
> say.hello <- function() + { + print("Hello, World!") + }
Get R for Everyone: Advanced Analytics and Graphics, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.