<- 10
x
<- function(x){
g02 <- x + 1
x return(x)
}
g02(x)
[1] 11
+ 1 x
[1] 11
For each question, predict what will happen when the code is run. Then run the code and check whether your prediction was correct.
x
is 10, g02(x)
returns 11. But values defined inside a function don’t impact the global environment, so calling g02
doesn’t change the value of x
. Therefore x + 1
still returns 11
.<- 10
x
<- function(x){
g02 <- x + 1
x return(x)
}
g02(x)
[1] 11
+ 1 x
[1] 11
x
is 10, g02(x)
returns 11. This output is stored in x
, so the variable x
has been overwritten and is now 11
. When we run x + 1
, we therefore get 12
.<- 10
x
<- function(x){
g02 <- x + 1
x return(x)
}
<- g02(x)
x + 1 x
[1] 12
g02(20)
, which is 19. This output is then used directly as the input for a second call to g02
, and g02(19)
returns 18
.<- function(y){
g02 <- y - 1
y return(y)
}
g02(g02(20))
[1] 18
integrate()
and an anonymous function to find the area under the curve for the following functions:y = x^2 - x
for x in \([0, 1]\)y = sin(x) + cos(x)
for x in \([-\pi, \pi]\)y = exp(x)/x
for x in \([10, 20]\)integrate(function(x) {x^2 - x}, 0, 1)
-0.1666667 with absolute error < 1.9e-15
integrate(function(x) {sin(x) + cos(x)}, -pi, pi)
5.231803e-16 with absolute error < 6.3e-14
integrate(function(x) {exp(x)/x}, 10, 20)
25613160 with absolute error < 2.8e-07