Base R Cheatsheet Getting Help Accessing the help files ?mean Get help of a particularfunction. help.search('weighted mean') Search the help files for a word or phrase. help(package = 'dplyr') Find help for a package. More about an object str(iris) Get a summary of an object's structure. class(iris) Find the class an object belongs to. Using Packages install.packages('dplyr') Download and install a package from CRAN. library(dplyr) Load the package into the session, making al its functions available to use. dplyr::select Use a particularfunction from a package. data(iris) Load a built-in dataset into the environment. Working Directory getwd() Find the current working directory (where inputs are found and outputs are sent). setwd('C://file/path') Change the current working directory. Use projects in RStudio to set the working directory to the folder you are working in. Vectors Programming '-1 Creating Vectors c(2, 4, 6) 2 4 6 Join elements into a vector 2:6 2 3 4 5 6 An integer sequence seq(2, 3, by=0.5) 2.0 2.5 3.0 A complex sequence rep(l:2, times=3) 12 12 12 Repeat a vector rep(l:2, each=3) 1112 2 2 Repeat elements of a vector Vector Functions sort(x) Return x sorted. table(x) See counts of values. rev(x) Return x reversed. unique(x) See unique values. Selecting Vector Elements By Position x[4] The fourth element. x[-4] x[2:4] x[-(2:4)] x[c(l, 5)] x[x == 10] x[x < 0] All but the fourth. Elements two to four. All elements except two to four. Elements one and five. By Value Elements which are equal to 10. All elements less than zero. x[x %in% c(l, 2, 5)] Elements in the set 1, 2, 5. x['apple'] Named Vectors Element with name 'apple'. For Loop While Loop for (variable in sequence){ Do something } while (conditionH Do something } Example Example for (i in 1:4){ j <- i + 10 printlj) } while (i < 5){ print(i) i <- i + 1 } If Statements Functions if (conditionH Do something } else { Do something different } function_name <- function(var){ Do something return(new_variable) Example if (i > 3){ print('Yes') } else { print!'No') } Example square <- function(x){ squared <- x*x return(squared) Reading and Writing Data Also see the readr package. Input Ouput Description df <- read.table!'file.txt') write.table(df, 'file.txt') Read and write a delimited text file. Read and write a comma df <- read.csv('file.csv') write.csv(df, 'file.csv') separated value file. This is a special case of read.table/ write.table. load('file.RData') save(df, file = 'file.Rdata') Read and write an R data file, a file type special for R. a == b Are equal a > b Greater than a >= b Greater than or equal to is.na{a) Is missing a != b Not equal a < b Less than a <= b Less than or equal to is.null(a) Is null RStudio® is a trademark of RStudio, Inc. • CC BY Mhairi McNeill • rnhairihrncneill@grnail.corn Learn more at web page orvignette • package version • Updated: 3/15 Types Converting between common data types in R. Can always go from a higher value in the table to a lower value. as.logical as.numeric as.character as.factor TRUE, FALSE, TRUE 'ľ, '0 levels: Boolean values (TRUE or FALSE). Integers or floating point numbers. Character strings. Generally preferred to factors. Character strings with preset levels. Needed for some statistical models. Maths Functions log(x) exp(x) max(x) min(x) rouncKx, n) signif(x, n) cor(x, y) Natural log. Exponential. Largest element. Smallest element. sum(x) mean(x) median(x) quantile(x) Round to n decimal rank(x) places. Round to n significant figu res. Correlation. sd(x) Sum. Mean. Median. Percentage quantiles. Rankof elements. The variance. The standard deviation. Variable Assignment > a <- 'apple' > a [1] 'apple' The Environment ls() rm(x) rmdist = IsO) List all variables in the environment. Remove x from the environment. Remove all variables from the environment. You can use the environment panel in RStudio to browse variables in your environment. Matrices m <- matrix(x, nrow = 3, ncol = 3) Create a matrix from x. j m[2, ] - Select a row ■ m [ , 1] - Select a column I m[2, 3] - Select an element Lists t(m) Transpose m %*% n Matrix Multiplication solve(m, n) Find x in: m * x = n I <- list(x = 1:5, y = c( 'a', 'b')) A list is a collection of elements which can be of different types. l[[2]] Second element of 1. Also see the dplyr package. Ul] New list with l$x l['y'] New list with Element named only the first only element element. ' named y. Data Frames df <- data.frame(x = 1:3, y = c('a', 'b', 'c')) A special case of a list where all elements are the same length. List subsetting df$x df[[2]] J 2 b Understanding a data frame Viewldf) Seethe full data 3 c frame. Matrix subsetting headldf) See the first 6 'OWS. df[ , 2] df[2, ] df[2, 2] nrow(df) Number of rows. | ncoKdf) Number of columns. dim(df) Number of columns and rows. cbind iind columns. rbind - Bind rows. Strings pastelx, y, Sep = ' paste(x, collapse = grep(pattern, x) Also see the stringr package. ) Join multiple vectors together. ' ) Join elements of a vector together. Find regular expression matches in x. gsub(pattern, replace, x) Replace matches in x with a string. toupper(x) Convertto uppercase. tolower(x) Convertto lowercase. nchar(x) Number of characters in a string. Factors factor(x) Turn a vector into a factor. Can set the levels of the factor and the order. cut(x, breaks = 4) Turn a numeric vector into a factor by 'cutting' into sections. Statistics lm(y ~ x, data=df) Linear model. glm(y ~ x, data=df) Generalised linear model. summary Get more detailed information out a model. t.test(x, y) Perform a t-testfor difference between means. pairwise.t.test Perform a t-test for paired data. prop.test Test fo r a difference between proportions. aov Analysis of va riance. Distributions Random Variates Density Function Cumulative Distribution Quantile Normal rnorm dnorm pnorm qnorm Poisson rpois dpois ppois qpois Binomial rbinom dbinom pbinom qbinom Uniform runif dunif punif qunif Also see the ggplot2 package. plot(x) Values of x in order. Dates plot(x, y) Values of x against y. hist(x) Histogram of See the lubridate package. RStudio® is a trademark of RStudio, Inc. • CC BY Mhairi McNeill • mhairihmcneill@gmail.com • 844-448-1212 ■ rstudio.com Learn more at web page orvignette • package version • Updated: 3/15