`+`
function (e1, e2) .Primitive("+")
sd
function (x, na.rm = FALSE)
sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x),
na.rm = na.rm))
<bytecode: 0x559bcb448a58>
<environment: namespace:stats>
and debugging
University of Luxembourg
Monday, the 24th of March, 2025
You will learn to:
(in ) Everything that exists is an object. Everything that happens is a function call.
— John Chambers Creator of the S language, predecessor of
The most important thing to understand about is that functions are objects in their own right. You can work with them exactly the same way you work with any other type of object.
— Hadley Wickham, Advanced R
Type names without ()
<-
and the keyword function
to store a function in an objectf
will not execute the code inside the function()
i.e. f()
in our examplereturn
something: here NULL
(the empty element)source: Hadley Wickham, Advanced R
[1] "Hello from basv!"
[1] "Hello from basv!"
return
Functions return the output of the last command
Error in f(): argument "z" is missing, with no default
[1] 3
Function environments are enclosed, the z
formal has nothing to do with Global Env z
.
Environments are enclosed, but if a variable is not found, it is searched in the parent: Global Env
Source: Hadley Wickham Advanced R
df
is actually a function (density for F), closures are a special kind of functions
Source: Jenny Bryan debugging
[1] 3
[1] 1.5
Error in 3/i: non-numeric argument to binary operator
Error message not so clear
See also the article by Jonathan McPherson about Debugging with RStudio
reprex
Error: Problem with `summarise()` input `top`.
x no applicable method for 'slice_max' applied
to an object of class "c('double', 'numeric')"
ℹ Input `top` is `slice_max(joer)`.
ℹ The error occurred in group 1: id = "0012".
reprex
usage and renders:library(dplyr, warn.conflicts = FALSE)
ToothGrowth |>
# should be slice_max(len, n = 2, by = supp) only
mutate(top = slice_max(len, n = 2),
.by = supp)
#> Error in `mutate()`:
#> ℹ In argument: `top = slice_max(len, n = 2)`.
#> ℹ In group 1: `supp = VC`.
#> Caused by error in `slice_max()`:
#> ! `order_by` is absent but must be supplied.
Created on 2024-02-29 with reprex v2.1.0
We know is flexible and not rigorous enough regarding indentation and style.
Thus, to make code looks more alike and consistent, we need to follow some guidelines
}
on its own lineis_even
You should make it work without a function first. Then encapsulate it to a function.
Once done, send it back to moodle in dedicated assignment.
is_even(1)
is_even(2)
is_even(NA)
[1] "for 1:"
[1] FALSE
[1] "for 2:"
[1] TRUE
[1] "for NA:"
Error: argument n should be a number!
You learned to:
Acknowledgments 🙏 👏
Thank you for your attention!