2018
Everything that is called in R is a function.
Everything that is created in R is an object.
we can easily work without touching the mouse.
R is object oriented and vector based.
x <- 1:10
)y
the root of the square of x
logical
> integer
> double
> complex
> character
Integer
or Double
are by deault Numeric
numeric()
as.numeric()
(decimal place is cut off by as.integer()
)is.numeric()
typeof()
Re()
and Im()
complex()
as.complex()
is.complex()
TRUE (1)
or FALSE (0)
0
and 1
)logical()
as.logical()
is.logical()
character
values are strings, alphanumeric values of arbitrary lengthcharacter
is the most open and confined data type in R" "
character()
as.character()
is.character()
POSIXct
(ct
calendar time) and POSIXlt
(lt
local time)1970-01-01 00:00:00 UTC
as.POSIXct()
and strptime()
)format()
or strftime()
NA
(i.e., type logical
), test with is.na()
0 / 0
) cause the type NaN
(Not a Number)NULL
-Object is used to describe that an object is not present.NULL
has no data type and cannot be converted.str()
col
)c()
(combine) or seq()
(sequence)length()
c(1, 2, 3, 4:10)
, seq(from = 1, to = 10, by = 2)
, c(c(1, 2, 3), seq(4, 6), 7:10)
rows
) and n columns (cols
)matrix(data, nrow, ncol)
rbind()
(row-bind) and cbind()
(col-bind)as.matrix()
as.numeric()
(or as.character()
etc.)length()
nrow()
, ncol()
, dim()
X <- matrix(data = 1:10, nrow = 2) dim(X)
## [1] 2 5
nrow(X)
## [1] 2
t()
, diagonale diag()
array(data, dim)
)names()
)rownames()
)data.frame()
as.data.frame()
unlist()
length()
nrow()
, ncol()
, dim()
x <- 1:3 y <- c("a", "b", "c") d <- data.frame(x = x, y = y) str(d)
## 'data.frame': 3 obs. of 2 variables: ## $ x: int 1 2 3 ## $ y: Factor w/ 3 levels "a","b","c": 1 2 3
names(d)
## [1] "x" "y"
names()
)list()
or vector(mode = "list", length = n)
as.list()
unlist()
length()
x <- 1:3 y <- c("a", "b", "c") l <- list(x = x, y = y) str(l)
## List of 2 ## $ x: int [1:3] 1 2 3 ## $ y: chr [1:3] "a" "b" "c"
l
## $x ## [1] 1 2 3 ## ## $y ## [1] "a" "b" "c"
data(volcano) V <- raster::raster(x = volcano) str(V)
## Formal class 'RasterLayer' [package "raster"] with 12 slots ## ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots ## .. .. ..@ name : chr "" ## .. .. ..@ datanotation: chr "FLT4S" ## .. .. ..@ byteorder : chr "little" ## .. .. ..@ nodatavalue : num -Inf ## .. .. ..@ NAchanged : logi FALSE ## .. .. ..@ nbands : int 1 ## .. .. ..@ bandorder : chr "BIL" ## .. .. ..@ offset : int 0 ## .. .. ..@ toptobottom : logi TRUE ## .. .. ..@ blockrows : int 0 ## .. .. ..@ blockcols : int 0 ## .. .. ..@ driver : chr "" ## .. .. ..@ open : logi FALSE ## ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots ## .. .. ..@ values : num [1:5307] 100 100 101 101 101 101 101 100 100 100 ... ## .. .. ..@ offset : num 0 ## .. .. ..@ gain : num 1 ## .. .. ..@ inmemory : logi TRUE ## .. .. ..@ fromdisk : logi FALSE ## .. .. ..@ isfactor : logi FALSE ## .. .. ..@ attributes: list() ## .. .. ..@ haveminmax: logi TRUE ## .. .. ..@ min : num 94 ## .. .. ..@ max : num 195 ## .. .. ..@ band : int 1 ## .. .. ..@ unit : chr "" ## .. .. ..@ names : chr "" ## ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots ## .. .. ..@ type : chr(0) ## .. .. ..@ values : logi(0) ## .. .. ..@ color : logi(0) ## .. .. ..@ names : logi(0) ## .. .. ..@ colortable: logi(0) ## ..@ title : chr(0) ## ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots ## .. .. ..@ xmin: num 0 ## .. .. ..@ xmax: num 1 ## .. .. ..@ ymin: num 0 ## .. .. ..@ ymax: num 1 ## ..@ rotated : logi FALSE ## ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots ## .. .. ..@ geotrans: num(0) ## .. .. ..@ transfun:function () ## ..@ ncols : int 61 ## ..@ nrows : int 87 ## ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot ## .. .. ..@ projargs: chr NA ## ..@ history : list() ## ..@ z : list()
x
from the numbers 0 to 5y
from six arbitrary lettersz
. Which data type do you expect for z
?x
to a logical vector x2
x
, y
and z
x
into a mastrix X
with two linesX
D
from x
and y
L
L
to "A"
and "B"
X
, D
and L
. What are the differences and commonalities?By the way, Hadley Wickham's Advanced R is a warm recommendation.
Libraries are no packages! Libraries contain packages. You pull a package from a library.
Working with packages simply saves time and brain cells
What do you think? What belongs to an R package?
A working examples (you don't want to rely on the documentation, only)
A set of further stuff that will be covered later
Title: Environmental seismology toolbox Description: A collection of functions to handle seismic data for the purpose of investigating the seismic signals emitted by Earth surface processes. The package supports inporting standard formats, data preparation and analysis techniques and data visualisation.
importFrom()
in the file NAMESPACE, instead.Authors@R: person("First", "Last", email = "first.last@example.com", role = c("aut", "cre"))
citation("PACKAGENAME")
to see how a package should be citedSince end of 2017, CRAN supports ORCID
Authors@R: person(..., comment = c(ORCID = "0000-0002-9079-593X"))
License: file LICENSE
) or a keyword of standard licenses (read more):
They are more than just counters, they define dependency satisfactions
Make use of a NEWS file to announce version history and changes.
Omitting it means, nobody will be able to use your package
Additional documentation is covered by vignettes (not covered here)
In R, documentation in *.Rd
-files is formalised and follows a pseudo LaTeX scheme (short version, long version)
roxygen2
inlinedocs
(no longer updated)*.rda
files (generated with save()
)data
src
will be compiled during installationinst
will be copied to main directoryPffffft, a lot of dense and boring input, right?
The task: Think about and collect the essential items for your own package. Note the results in a plain text document for later use. Time: about 4 minutes.
We will need this material soon to build a package, … an empty one, … which will finally only have one function.
The task: Think about and collect the essential items for your own package. Note the results in a plain text document for later use. Time: about 4 minutes.
We will need this material soon to build a package, … an empty one, … which will finally only have one function.
Already need a short reminder? :)
Alternatively use devtools::create("path/to/package/pkgname")
Alternatively (DON'T) use package.skeleton()
. It will create an overloaded package template that needs more modification.
exportPattern("^[[:alpha:]]+")
, i.e., every function is exported!a <- 10:50 print(a) plot(a) b <- 210:250 plot(a, b) A <- a * b c <- 5 V <- A * c print(A) print(V) plot(a,V)
a <- 10:50 b <- 210:250 c <- 5 A <- a * b V <- A * c plot(a) plot(a, b) plot(a,V) print(a) print(A) print(V)
## define object geometry a <- 10:50 b <- 210:250 c <- 5 ## calculate area and volume A <- a * b V <- A * c ## plot object dimensions plot(a) plot(a, b) plot(a, V) ## print values print(a) print(A) print(V)
f <- function(a, b, c) { ## calculate area and volume A <- a * b V <- A * c ## plot object dimensions plot(a) plot(a, b) plot(a, V) ## return values return(list(A = A, V = V)) }
f <- function(a, b, c, plot = TRUE) { ## calculate area and volume A <- a * b V <- A * c ## optionally plot object dimensions if(plot == TRUE) { plot(a) plot(a, b) plot(a, V) } ## return values return(list(A = A, V = V)) }
f(a = 10, b = 100, c = 5, plot = FALSE)
## $A ## [1] 1000 ## ## $V ## [1] 5000
FUNCTION_NAME(ARUMENT_1, ARGUMENT_2) {FUNCTION BODY}
Ooops, what did we forget?
Function documentation (in a separate file)
\name{f} \alias{f} \title{Calculate and plot cuboid areas and volumes.} \usage{f(a, b, c, plot = TRUE)} \arguments{ \item{a}{\code{Numeric} vector, length of the cuboid.} \item{b}{\code{Numeric} vector, width of the cuboid.} \item{c}{\code{Numeric} vector, height of the cuboid.}} \value{A list with cuboid area and volume.} \description{The function takes numeric vectors of the cardinal dimensions of a cuboid object and calculates area and volume. The results can optionally be plotted.} \examples{f(a = 10, b = 100, c = 5, plot = FALSE)} \author{Michael Dietze}
Another brief function example
f <- function(x, p = 2) { ## calculate the power of x y <- x^p ## return value return(y) }
Can be rewritten like this:
#' @title Calculate the power of a vector # TITLE #' #' @description The function calculates something # DESCRIPTION #' #' @details The function simply combines the arguments. # DETAILS #' #' @param x input vector # ARGUMENTS #' @param p power exponent # ARGUMENTS #' @return vector of the power p of x. # VALUE #' @author Michael Dietze # AUTHOR(S) #' @examples #' f(x = 10, p = 3) # EXAMPLES #' @export # NAMESPACE ENTRY f <- function(x, p = 2) { # USAGE return(x^p) }
And become something like:
'roxygen2' is a package that parses function source files for tags (e.g., #' @param) and converts them to the structure of a *.Rd
-file.
Third and further set of lines becomes details (optional)
Further down follow tagged items
@param
- Function arguments, note argument and then description@return
- Function value@examples
- Examples section@export
- Namespace export, usually the function name@seealso
- Related functions to link to@keywords
- Well, keywords@section
- Arbitrary sections to further structure the documentation\emph{}
, \strong{}
, \code{}
)\code{\link{}}
, \href{}{}
)\enumerate{}
, \itemize{}
)\eqn{}
, \deqn{}
)\tabular{}{\tab \cr}
)Luminescence::analyse_baSAR.R
Are we finished? Not yet.
@format
- Overview of data structure (copy-paste output of str()
)@source
- Source of the data set, e.g., the internet linkR/DATA_SET.R
#' Ten numbers from 1 to 10 #' #' A dataset containing ten ordered natural numbers #' #' @format A vector with 10 variables: #' int [1:10] 1 2 3 4 5 6 7 8 9 10 "x"
NULL
-objectPACKAGE_NAME-package.R
in R/
#' A package of diverse functions #' #' The package is used to store all my functions, save from my brain. #' #' @docType package #' @name PACKAGE_NAME #' @import stats #' @importFrom utils read.table, write.table NULL
In a nutshell: documenting package and datasets means:
#' eseis: Environmental Seismology Toolbox #' #' This package eseis provides functions to read/write seismic data files... #' #' @name eseis #' @aliases eseis #' @docType package #' @author Michael Dietze #' @importFrom graphics image plot axis axis.POSIXct box mtext NULL #' Seismic trace of a rockfall event. #' #' The dataset comprises the seismic signal of a rockfall. #' #' @name rockfall #' @docType data #' @format The format is: num [1:98400] 65158 65176 65206 65194 65155 ... #' @examples #' ## load example data set and plot it. #' data(rockfall) #' plot(rockfall, type = "l") "rockfall"
Pffffft, no more details please!
Task A: Create a simple example dataset: a sequence of numbers from 1 to 10 called x
. Save it as x.rda
in your package. Maybe you need to create a directory called data
, first?
Task B: Write a function that can multiply a numeric vector (x
) by a constant (c
, default is 1
) and return the result. Document the function using roxygen2 tags, including an example.
Task C: Document the package and the example data set using roxygen2.
Time: 5-8 min
Task A
x <- seq(from = 1, to = 10) save(x, file = "data/x.rda")
Task B
#' Multiply a vector by a constant #' #' The function uses simple R functionalities to multiply a numeric #' vector x by a constant c and returns the resulting vector. #' #' @param x Numeric vector to be multiplied #' @param c Numeric value multiplicator, default is \code{1} #' @return Numeric vector, product of \code{x} and \code{c} #' @author Michael Dietze #' @examples #' data(x) #' mtp(x = x, c = 2) #' @export mtp mtp <- function(x, c = 1) { return(x * c) }
Task C
#' toolbox: A growing set of handy functions #' #' This package contains one function to help solving problems in R. #' #' @name toolbox #' @docType package #' @author Michael Dietze NULL #' Numeric vector #' #' The dataset contains a numeric vector from 1 to 10. #' #' @name x #' @docType data #' @format The format is: num [1:10] 1 2 3 4 5 6 7 8 9 10 #' @examples #' ## load example data set and plot it. #' data(x) #' plot(x) "x"
PACKAGE_VERSION_tar.gz
-file in your R directoryCheck
stops with an error? See where the error happened:
Now, that is it. All that is left is for you to build your package. So, go ahead!