You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
add_2_vectors <- function(x, y, remove.na = TRUE) {
2294
+
sum(x, y, na.rm = remove.na)
2295
+
}
2296
+
add_2_vectors(x = a, y = b)
2297
+
```
2298
+
2299
+
Most R functions have parameters to ignore the presence of missing values.
2300
+
2301
+
## Control of execution
2302
+
2303
+
For a program or a function to do interesting calculations it is necessary to operate repetitively over data structures like vectors and lists to generate new values or a single one representing the desired target.
2304
+
2305
+
The line by line flow of execution of an R program can be altered with the use of functions or statements. Both methods are available in R. Using functions leads to a functional style of programming while using statements leads to procedural style.
2306
+
2307
+
### The procedural statements
2308
+
2309
+
The procedural style syntax for looping or iterating uses the following structures:
The functional forms of these structures can be formulated depending on the object that the user-function is applied to. For a vector the applications are straight forward.
2334
+
2335
+
The functional and procedural styles of writing programs are equivalent, however for the majority of the applications in statistics and linear algebra R is optimized to use the functional style. More recently packages like `purr` from the `tidyverse` syntax have added all the functional tools that make it extremely succinct to express standard transformations on vectorized data structures like lists, matrices, arrays, and data frames.
2336
+
2337
+
Let's have a look at concrete examples.
2338
+
2339
+
### Iterating over a vector
2340
+
2341
+
2342
+
First illustrate the `sapply` function to square all the elements of a numeric vector.
In functional style this is done via subsetting. In procedural style a combination of a for-loop and the conditional-statements with if-else can achieve the same result. Let us have a look at the air fare to sun destinations at or below $1200.
0 commit comments