Skip to content

Commit

Permalink
modified lab and slides of loops
Browse files Browse the repository at this point in the history
  • Loading branch information
RedondoMA committed Oct 18, 2024
1 parent 6a6ee1c commit 7da806f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
22 changes: 21 additions & 1 deletion lab_loops.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ dfr.info <- function(dfr) {
dfr.info(dfr1)
```

5. **Extra exercise** A variation of exercise 3: Create a data frame with three columns: one numeric, one logical, and one character vector. Write a loop that loops over the columns and reports the sum of the column values if it is numeric, the total number of `TRUE`s when is logical and the total number of characters if it is a character vector.
5. **Extra exercise-loops**. A variation of exercise 3: Create a data frame with three columns: one numeric, one logical, and one character vector. Write a loop that loops over the columns and reports the sum of the column values if it is numeric, the total number of `TRUE`s when is logical and the total number of characters if it is a character vector.
<details>
<summary><strong>Tips?</strong></summary>
To count number of characters, you can use `nchar` function. <br/>
Expand Down Expand Up @@ -212,6 +212,26 @@ for(i in 1:ncol(dfr2)) {
sum.vec
```

6. **Extra exercise-functions**. Create a function that will convert time in hours to time in minutes. The function should take a single argument, a numeric value of hours, and return a numeric value of minutes. Add an if clause inside of the function that will stop running the function and give an error if the hours provided are negative.
<details>
<summary><strong>Tip?</strong></summary>
You can read the documentation of the `stop()` function by typing `?stop` in the R console.
</details>

```{r,accordion=TRUE, error=T}
hours_to_mins <- function(hours) {
if (hours < 0) {
stop("Hours cannot be negative")
}
minutes <- hours * 60
return(minutes)
}
hours_to_mins(3.2)
#Now test it with a negative hour value
hours_to_mins(-3.26)
```


6. In all loops that we tried out we have created the variable where the output is saved outside the loop. Why is this?
</br>
Expand Down
5 changes: 1 addition & 4 deletions slide_r_elements_4.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,7 @@ h <- function(a = 1, b = d) {
---

name: everything_is_a_fn
exclude:true

# In R everything is a function

Expand All @@ -602,22 +603,18 @@ Because in R everything is a function
`+`
```

--

we can re-define things like this:

--

```{r fns.everything_2, echo=T}
`+` <- function(e1, e2) { e1 - e2 }
2 + 2
```

--

and, finally, clean up the mess...

--

```{r fns.everything_3, echo=T}
rm("+")
Expand Down

0 comments on commit 7da806f

Please sign in to comment.