R Module 12 - Functions
R Module 12 - Functions
Andrew Jaffe
January 9, 2016
Writing your own functions
functionName = function(inputs) {
< function body >
return(value)
}
Then you would run the 4 lines of the code, which adds it to your
workspace.
Writing your own functions
[1] 4
Writing your own functions
Note that your function will automatically return the last line of
code run:
[1] 4
And if your function is really one line or evaluation, like here, you do
not need the curly brackets, and you can put everything on one line:
[1] 4
Writing your own functions
Also note that functions can take multiple inputs. Maybe you want
users to select which element to extract
[1] 5
Writing a simple function
[1] 1
> sqdif(x=10,y=5)
[1] 25
> sqdif(10,5)
[1] 25
Writing your own functions
$Friday
day date
5 Friday 01/15/2010
12 Friday 01/22/2010
$Monday
day date
1 Monday 01/11/2010
8 Monday 01/18/2010
Custom functions in apply
You can also designate functions “on the fly”
$Friday
day date
5 Friday 01/15/2010
12 Friday 01/22/2010
$Monday
day date
1 Monday 01/11/2010
8 Monday 01/18/2010
$Saturday
day date
6 Saturday 01/16/2010
13 Saturday 01/23/2010
Simple apply
sapply() is a user-friendly version and wrapper of lapply by
default returning a vector, matrix, or array
$a
[1] 1
$b
[1] 2
$c
[1] "a"
$d
[1] boy
Levels: boy girl
a b c d
"1" "2" "a" "1"
a b c d
"1" "2" "a" "boy"