@@ -742,6 +742,8 @@ of the modulo is equal to `0`.
13 %% 2
```
3. Using your `even_test` function, write a new function `even_print` which will print "This number is even" or "This number is odd". You will need the `if else` statement and the function `print`. Find help on how to use them.
</div>
<details><summary>Solution 1 </summary>
...
...
@@ -772,7 +774,7 @@ even_test(3)
**Note :** A function can be written in several forms.
```{r VandAstep11small, include=TRUE}
```{r VandAstep11smal2, include=TRUE}
even_test2 <- function(x){
(x %% 2) == 0
}
...
...
@@ -783,6 +785,38 @@ even_test(3)
</details>
<details><summary>Solution 3 </summary>
<p>
```{r VandAstep13, include=TRUE}
even_print <- function(x){
if(even_test(x) == TRUE) {
print("This number is even")
} else {
print("This number is odd")
}
}
even_print(4)
even_print(3)
```
**Note :** There is no need to test whether a boolean variable (TRUE/FALSE) is TRUE or FALSE.
```{r VandAstep11small14, include=TRUE}
even_print <- function(x){
if(even_test(x)) {
print("This number is even")
} else {
print("This number is odd")
}
}
even_print(4)
even_print(3)
```
</p>
</details>
## Cleaning up
We can now clean your environment
...
...
@@ -872,7 +906,6 @@ To determine the type of the elements of a vector:
typeof(x)
```
```{r Vecstep6, include=TRUE}
typeof(x + 0.5)
x + 0.5
...
...
@@ -898,6 +931,51 @@ y
x == y
```
## Accessing values
There are multiple ways to access or replace values in vectors or other data structures. The most common approach is to use "indexing".
In the below, note that brackets `[ ]` are used for indexing, whereas you have already seen that parentheses `( )` are used to call a function and `{ }` to define function. It is very important not to mix these up.
Here are some examples that show how elements of vectors can be obtained by indexing.
You can use the position(s) of the value(s) in the vector
```{r index1, include=TRUE}
x <- c(1,5,7,8)
x[4]
x[c(1,3,4)]
```
You can use booleans to define which values should be kept.
```{r index2, include=TRUE}
x <- c(1,5,7,8,15)
x[c(TRUE,FALSE,TRUE,FALSE,TRUE)]
x[c(FALSE,TRUE)] # Bolean vector is reuse if it is not of the same size of the vector to index