Skip to content

Commit

Permalink
Comment the recursion exercise
Browse files Browse the repository at this point in the history
  • Loading branch information
nimarafati committed Oct 24, 2023
1 parent d7243f4 commit 3744a7f
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions lab_loops.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ while (x < 100000) {
head(while.sum)
```

3. Create a data frame with two numeric and one character vector. Write a loop that loops over the columns and reports the sum of the column values if it is numeric and the total number of characters if it is a character vector.
3. Create a data frame with two numeric and one character vector. Write a loop that loops over the columns and reports the sum of the column values if it is numeric and the total number of characters if it is a character vector.
**Tips** to count number of characters, you can use `nchar` function.

```{r,accordion=TRUE}
vector1 <- 1:10
Expand All @@ -114,22 +115,23 @@ sum.vec

```{r,accordion=TRUE}
dfr.info <- function(dfr) {
sum.vec <- vector()
for (i in 1:ncol(dfr)) {
if (is.numeric(dfr[,i])) {
sum.vec[i] <- mean(dfr[,i])
} else {
sum.vec[i] <- sum(nchar(dfr[,i]))
}
}
sum.vec
sum.vec <- vector()
for (i in 1:ncol(dfr)) {
if (is.numeric(dfr[,i])) {
sum.vec[i] <- mean(dfr[,i])
} else {
sum.vec[i] <- sum(nchar(dfr[,i]))
}
}
sum.vec
}
```

5. Read up on the if-else function in R. If possible use the if-else function to answer question 3.

6. In all loops that we tried out we have created the variable where the output is saved outside the loop. Why is this?

<!--
7. <i class="fas fa-exclamation-circle"></i> **Advanced:** At the lecture an approach to calculate factorials were implemented using recursion (function calling itself). Here we instead will have a go at generating Fibonacci numbers. A fibonacci number is part of a series of number with the following properties:
The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two. Hence:
Expand All @@ -141,3 +143,4 @@ or
`1, 1, 2, 3, 5, 8, 13, 21, ...`
Try to generate such a series using a recursive approach.
-->

0 comments on commit 3744a7f

Please sign in to comment.