Consider the following simple function
v = 5 fun1 = function() { v = 0 return(v) } fun1()
r
## fun1 uses the local variable v
Delete line 3 in the above piece of code. Now change fun1()
to allow
v
to be passed as an argument, i.e. we can write fun1(5)
. Call
this function to make sure it works.
r
fun1 = function(v) {
return(v)
}
fun1(10)
fun2 = function(x = 10) { return(x) } fun3 = function(x) { return(x) }
Why does
r
fun2()
work, but this raises an error
r
fun3()
```r
```
Change fun2
so that it returns x*x
.
r
fun2 = function(x = 10) {
return(x * x)
}
a = 2 total = 0 for (blob in a:5) { total = total + blob }
In the code above, delete line 1. Now put the above code in a function called fun5
,
where a
is passed as an argument, i.e. we can call
fun5(1)
r
fun5 = function(a) {
total = 0
for (blob in a:5) {
total = total + blob
}
return(total)
}
fun5(1)
Alter the code so that the for
loop goes from a
to
b
, rather than a
to $5$. Allow b
to be passed as an
argument, i.e. we can call fun5(1,5)
.
r
fun5 = function(a, b) {
total = 0
for (blob in a:b) {
total = total + blob
}
return(total)
}
fun5(1, 5)
Change fun5
so that it has default arguments of
a = 1
and b = 10
. Try calling fun5(5)
. Why do we get the answer outputted?
r
fun5 = function(a=1, b=10) {
total = 0
for (blob in a:b) {
total = total + blob
}
return(total)
}
fun5(5)
Solutions are contained within this package:
vignette("solutions2", package = "jrProgramming")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.