<- function(arguments) {
my_fun
"body of code"
}
(AST230) R for Data Science
Functions are just another R object
Comas separate more than one argument
The following codes simulate an experiment “rolling a dice”
Write a function roll()
for the simulation
roll()
has no arguments, and it will return a number between 1 to 6roll()
, first run the written R function codes in the R console. Then run roll()
The number of heads in 10 fair coin toss
The number of heads in 20 fair coin toss
The number of heads in 100 fair coin toss
The size
argument of sample()
is changing for different number of coin toss
Can you write a function in R that takes how many times to toss a fair coin and prints us how many times it lands on heads?
Tossing coins 200/500 times
What will happen if you run the function without specifying the argument
Default value of an argument can be specified
E.g., times = 100
will be considered if times
is not supplied!
Write an R function roll_dice()
that rolls a dice n
times (where n
is 1 or more) and returns the sum of the dice rolls.
Write an R function toss_bias_coins()
that tosses a biased coin n
times (where n
is 1 or more times) and returns the number of heads. The probability of getting heads is 0.70.
Write an R function that can simulate flipping a fair or biased coin. The probability of getting heads should not always be 0.70, but any value between 0 and 1!
help("mean")
or “?mean” to check the detail of mean()
The help.search()
function searches through the help documentation, code demonstrations and package vignettes and displays the results as clickable links for further exploration
Another useful function is apropos()
Pro Tip
RStudio snippet can save your time. Type fun
and wait some milliseconds to see suggestions (press Tab if they don’t appear). Select (or press Tab) on the snippet option to insert it. You can see and customize your snippets from Tools>Global Options>Code.