Introduction to Writing Functions in R
Richie Cotton
Data Evangelist at DataCamp
R.version.string
"R version 3.5.3 (2019-03-11)"
Sys.info()[c("sysname", "release")]
sysname release
"Linux" "4.14.106-79.86.amzn1.x86_64"
loadedNamespaces()
[1] "Rcpp" "grDevices" "crayon"
[4] "dplyr" "assertthat" "R6"
[7] "magrittr" "datasets" "pillar"
[10] "rlang" "utils" "praise"
[13] "rstudioapi" "graphics" "base"
[16] "tools" "glue" "purrr"
[19] "yaml" "compiler" "pkgconfig"
[22] "stats" "tidyselect" "methods"
[25] "tibble"
session <- function() {
r_version <- R.version.string,
operating_system <- Sys.info()[c("sysname", "release")],
loaded_pkgs <- loadedNamespaces()
# ???
}
session <- function() {
list(
r_version = R.version.string,
operating_system = Sys.info()[c("sysname", "release")],
loaded_pkgs = loadedNamespaces()
)
}
session()
$r_version
[1] "R version 3.5.3 (2019-03-11)"
$operating_system
sysname release
"Linux" "4.14.106-79.86.amzn1.x86_64"
$loaded_pkgs
[1] "Rcpp" "grDevices" "crayon"
[4] "dplyr" "assertthat" "R6"
[7] "magrittr" "datasets" "pillar"
[10] "rlang" "utils" "praise"
[13] "rstudioapi" "graphics" "base"
[16] "tools" "glue" "purrr"
[19] "yaml" "compiler" "pkgconfig"
[22] "stats" "tidyselect" "methods"
[25] "tibble"
library(zeallot)
c(vrsn, os, pkgs) %<-% session()
vrsn
"R version 3.5.3 (2019-03-11)"
os
sysname release
"Linux" "4.14.106-79.86.amzn1.x86_64"
month_no <- setNames(1:12, month.abb)
month_no
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1 2 3 4 5 6 7 8 9 10 11 12
attributes(month_no)
$names
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul"
[8] "Aug" "Sep" "Oct" "Nov" "Dec"
attr(month_no, "names")
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul"
[8] "Aug" "Sep" "Oct" "Nov" "Dec"
attr(month_no, "names") <- month.name
month_no
January February March April May
1 2 3 4 5
June July August September October
6 7 8 9 10
November December
11 12
orange_trees
# A tibble: 35 x 3
Tree age circumference
<ord> <dbl> <dbl>
1 1 118 30
2 1 484 58
3 1 664 87
4 1 1004 115
5 1 1231 120
6 1 1372 142
7 1 1582 145
8 2 118 33
9 2 484 69
10 2 664 111
# … with 25 more rows
attributes(orange_trees)
$names
[1] "Tree" "age"
[3] "circumference"
$row.names
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
[16] 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
[31] 31 32 33 34 35
$class
[1] "tbl_df" "tbl" "data.frame"
library(dplyr)
orange_trees %>%
group_by(Tree) %>%
attributes()
$names
[1] "Tree" "age" "circumference"
$row.names
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
[19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
$class
[1] "grouped_df" "tbl_df" "tbl" "data.frame"
$groups
# A tibble: 5 x 2
Tree .rows
<ord> <list>
1 3 <int [7]>
2 1 <int [7]>
3 5 <int [7]>
4 2 <int [7]>
5 4 <int [7]>
Model objects are converted into 3 data frames.
function | level | example |
---|---|---|
glance() |
model | degrees of freedom |
tidy() |
coefficient | p-values |
augment() |
observation | residuals |
Introduction to Writing Functions in R