What's my type?
You've just seen four functions that help you determine what type of variable you're working with. class()
(docs) and typeof()
(docs) are important and will come in handy often. mode()
(docs) and storage.mode()
(docs) mostly exist for compatibility with the S programming language.
In this exercise, you will look at what these functions return for different variable types. There are some rarer types that you may not have come across yet.
array
(docs): Generalization of a matrix with an arbitrary number of dimensions.formula
(docs): Used by modeling and plotting functions to define relationships between variables.
Also note that there are three kinds of functions in R.
- Most of the functions that you come across are called
closure
s. - A few important functions, like
length()
(docs) are known asbuiltin
functions, which use a special evaluation mechanism to make them go faster. - Language constructs, like
if
(docs) andwhile
(docs) are also functions! They are known asspecial
functions.
This exercise is part of the course
Object-Oriented Programming with S3 and R6 in R
Exercise instructions
The type_info()
function has been predefined in your workspace to return the class()
, mode()
, typeof()
, and storage.mode()
of its input. (Type type_info
in the console to see how it works.)
- Create
some_vars
, the list of example objects provided in the editor. - Use
lapply
to loop over the elements ofsome_vars
, callingtype_info()
on each of the example objects to explore their type.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Look at the definition of type_info()
type_info
# Create list of example variables
some_vars <- list(
an_integer_vector = rpois(24, lambda = 5),
a_numeric_vector = rbeta(24, shape1 = 1, shape2 = 1),
an_integer_array = array(rbinom(24, size = 8, prob = 0.5), dim = c(2, 3, 4)),
a_numeric_array = array(rweibull(24, shape = 1, scale = 1), dim = c(2, 3, 4)),
a_data_frame = data.frame(int = rgeom(24, prob = 0.5), num = runif(24)),
a_factor = factor(month.abb),
a_formula = y ~ x,
a_closure_function = mean,
a_builtin_function = length,
a_special_function = `if`
)
# Loop over some_vars calling type_info() on each element to explore them
___