- How do you write a new function in R?
- What are its parts? How many of each one?
March 4, 2020
name <- function(input) { commands; return(output) }
draw_person <- function(size) { draw_head(size) turtle_left(180) turtle_forward(size/2) turtle_left(90) draw_arm(size) turtle_left(180) draw_arm(size) turtle_left(90) turtle_forward(size*3/2) turtle_left(40) draw_leg(size) turtle_right(40) draw_leg(size) }
Write the functions draw_head()
, draw_arm()
and draw_leg()
.
Each function must leave the turtle in the same position and the same angle as before
Your function can move the turtle as you wish, but it must leave the turtle as it was at the beginning of the function
Each part commits to do something
Each part makes a promise
We promise to leave the turtle in the same position as we received it
draw_arm <- function(size) { turtle_forward(size) turtle_backward(size) } draw_leg <- function(size) { old_pos <- turtle_getpos() old_angle <- turtle_getangle() turtle_forward(size*3/2) turtle_left(90) turtle_forward(size/2) turtle_setangle(old_angle) turtle_setpos(old_pos[1], old_pos[2]) }
draw_head <- function(size) { turtle_right(90) turtle_forward(size/2) for(i in 1:3) { turtle_left(90) turtle_forward(size) } turtle_left(90) turtle_forward(size/2) turtle_left(90) }
The contract is this:
a
and b
a
and b
Let’s write a function for this
Answer now
if <> then
There are two version: if-then and if-then-else
These command takes one logic condition and one or two code blocks
Most of times we use only if-then
if(cond) { # do this only if `cond` is true }
if(cond) { # do this only if `cond` is true } else { # do this only if `cond` is false }
if(a<b) { answer <- a } else { answer <- b }
The contract is this:
a
, b
, and c
a
, b
, and c
Let’s write a function for this
Answer now
The contract is this:
x
x
Let’s write a function for this
Answer now
Make these functions using only for()
, if()
and indices. You cannot use the words min
or max
. The input is a vector called x
.
Please write the code of the following functions:
smallest_value(x)
. Returns the smallest element in x
.largest_value(x)
. Returns the largest element in x
.place_of_smallest(x)
. Returns the index of the smallest element in x
.place_of_largest(x)
. Returns the index of the largest element in x
.x <- sample(5:20, size=10, replace=TRUE) min(x) smallest_value(x)
The two results must be the same.
(We will study the function sample
later)