From 6ca7318826fb10924ce65567fa853651bfd3c14f Mon Sep 17 00:00:00 2001 From: Nima Rafati Date: Fri, 20 Oct 2023 09:35:55 +0200 Subject: [PATCH] Add base for loop and adjust `switch` example --- slide_r_elements_4.Rmd | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/slide_r_elements_4.Rmd b/slide_r_elements_4.Rmd index 698ba38..8b64d11 100644 --- a/slide_r_elements_4.Rmd +++ b/slide_r_elements_4.Rmd @@ -65,12 +65,26 @@ which denotes multiplication of elements $1 ... n$. It is important to learn how to translate these (and similar) formulas into the R language. --- -name: for_loop +name: for_loop_0 # Repeating actions — for loop One way to repeat an action is to use the **for-loop** +```{r for.loop.general, echo=T, eval = F} +for (var in seq) { + expr +} +``` + +--- +name: for_loop_1 + +# Repeating actions — for loop + +Example. + + ```{r for.loop, echo=T} for (i in 1:5) { cat(paste('Performing operation no.', i), '\n') @@ -252,7 +266,7 @@ Always try to know the size of the object you are going to create! --- name: if_clause -# To R or not to Python? — taking decisions, an if-clause +# An if-clause Often, one has to take a different course of action depending on a flow of the algorithm. You have already seen the **if-else** block. Let's print only odd numbers $[1, 10]$: @@ -351,8 +365,8 @@ If-else clauses operate on logical values. What if we want to take decisions bas ```{r switch, echo=T} switch.demo <- function(x) { switch(class(x), - logical = , - numeric = cat('Numeric or logical.'), + logical = cat('logical'), + numeric = cat('Numeric'), factor = cat('Factor.'), cat('Undefined') ) @@ -519,7 +533,7 @@ h <- function(a = 1, b = d) { h() ``` -> The above won't be possible in, e.g. C where values of both arguments have to be known before calling a function **eager evaluation**. +> The above won't be possible in, e.g. where values of both arguments have to be known before calling a function which is known as **eager evaluation**. --- name: everything_is_a_fn