knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
One of the most simple things we can do with R is to use it as a kind of calculator. We can do all elementary arithmetic operations:
>1 + 1 [1] 2 >1 - 1 [1] 0 >2 * 3 [1] 6 >2 / 3 [1] 0.6666667
Here we use '>' to denote the R prompt. It is used in the console to indicate that R is ready for a new command. The lines in between is the output given by R.
Most of the functionality in R comes from its functions. There are many functions we can use including the standard mathematical ones:
cos(3.1415) [1] -1 exp(0) [1] 1 log(1) [1] 0
We will discuss functions later on in this text in much more detail.
The results above are displayed but not stored. To do this we must give a name to the result. That is, we store the result in a variable. The results are now no longer displayed but using the variable name we can refer to it later.
Assigning a result in a variable is done using <-
. For example:
>five <- 3+2 > five [1] 5 > five + 1 [1] 6
Each variable has a class that determines for a large extend what we can do with it.
As mentioned above R is a modular language that we can extend using packages. We can load a package using the command library()
. So if we want to load the survival
package (in order to do survival analysis ) we type:
>library(survival)
Before we can load a library it must be installed. This can be done using the command install.packages(packagename)
where packagename
is the name of the package between single or double quotes. For example:
>install.packages('gamlss')
Some useful packages are lme4
for analyses with repeated measurements and mice
for multiple imputation.
The functions help
and ?
can be used to read the documentation on a particular subject (mostly functions). The package in which the function is defined must be loaded unless you use the package
parameter ofn the help function. For example: help('survreg' , package='survival')
.
Using help.search
and ??
we can search the documentation files in a more general way. The documentation for all installed packages is searched for topics that have specific words in the title.
>?library >help(install.packages) >help.search('logistic regression')
Some R packages are also documented with so called vignettes. You can browse the vignettes of a package using the function browseVignettes
, for example browseVignettes(package="survival")
.
Using the function RSiteSearch
you can search the documentation of all packages that are on CRAN (so it is like a google for R).
Another great source of help is the site 'Stack Overflow'. A site were people can ask all kinds of programming related questions.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.