Anonymous Example 1
Use an anonymous function to square all the values in the following
vector:
# Use an anonymous function to calculate the square of each element in a vector
numbers <- 1:40
sapply(numbers, \(y) y^2)
[1] 1 4 9 16 25 36 49 64 81 100 121 144 169 196
[15] 225 256 289 324 361 400 441 484 529 576 625 676 729 784
[29] 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600
numbers^2
[1] 1 4 9 16 25 36 49 64 81 100 121 144 169 196
[15] 225 256 289 324 361 400 441 484 529 576 625 676 729 784
[29] 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600
2Anonymous Example 2
Use an anonymous function to convert the vector from Fahrenheit to
Celsius:
sapply(temperatures_f, function(f) 5*(f-32)/9)
[1] 0 20 40 10
\[
C = \frac{5(F-32)}{9}
\]
Pipe Examples 1
Using the vector below, find the standard deviation using a pipe:
x %>% sd
[1] 1.167569
Pipe Examples 2
Chain pipe the previous results into the \(sin(x)\).
x %>% sd %>% sin
[1] 0.9197992
Pipe Examples 3
Chain pipe the previous results into \(e^x\).
x %>% sd %>% sin %>% exp
[1] 2.508787
Pipe Examples 4
Chain pipe the previous results into \(x^2+5x+4\)
x %>% sd %>% sin %>% exp %>% (\(x) x^2 +5*x+4)
[1] 22.83794
LS0tCnRpdGxlOiAiQ2xhc3MgOCIKYXV0aG9yOiAiSXNhYWMgUXVpbnRhbmlsbGEgU2FsaW5hcyIKZGF0ZTogImByIGZvcm1hdChTeXMudGltZSgpLCclbS0lZC0lWScpYCIKb3V0cHV0OiAKICBodG1sX25vdGVib29rOgogICAgdG9jOiB0cnVlCiAgICB0b2NfZmxvYXQ6IHRydWUKICAgIGNvZGVfZm9sZGluZzogaGlkZQotLS0KCiMjIEFub255bW91cyBFeGFtcGxlIDEKClVzZSBhbiBhbm9ueW1vdXMgZnVuY3Rpb24gdG8gc3F1YXJlIGFsbCB0aGUgdmFsdWVzIGluIHRoZSBmb2xsb3dpbmcgdmVjdG9yOgoKYGBge3J9CiMgVXNlIGFuIGFub255bW91cyBmdW5jdG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