# ACCA7022 Advanced Statistical Programming — R Function Reference Sheet # # Each entry gives the function name and its purpose, followed by example R code. # The examples are independent demonstrations, not one continuous analysis. # Run individual lines or sections in R/RStudio. # # Requirements: base R; ggplot2 for the visualisation section. # install.packages("ggplot2") # Run once if ggplot2 is not installed. # library(ggplot2) # Uncomment before running ggplot2 examples. # # The read.csv() example requires a file named Results.csv in the working directory. # The examples using mtcars use the dataset supplied with R. # Some ggplot2 examples create plot components (layers or mappings), rather than # complete plots; add these to a ggplot() expression to display them. # ========================================================================== # Workshop 1 – Introduction # ========================================================================== # c() — Combines values into a vector. c(2, 4, 6) # mean() — Calculates the arithmetic mean. mean(c(2,4,6)) # hist() — Draws a histogram of numeric data. hist(rnorm(100)) # sd() — Calculates sample standard deviation. sd(c(2,4,6)) # runif() — Generates uniformly distributed random values. runif(5, min=0, max=1) # sample() — Randomly samples or rearranges values. sample(1:10, 4) # sum() — Adds values together. sum(c(1,2,3)) # ========================================================================== # Workshop 2 – Vectors I # ========================================================================== # typeof() — Returns an object's internal data type. typeof(c(1,2,3)) # seq() — Creates a sequence of numbers. seq(1, 3, by=0.4) # ========================================================================== # Workshop 3 – Vectors II # ========================================================================== # length() — Returns the number of elements. length(c(4,5,6)) # is.na() — Identifies missing (NA) values. is.na(c(1,NA,3)) # is.null() — Tests whether an object is NULL. is.null(NULL) # rep() — Repeats values or sequences. rep(c(2,3,4), each=2) # ========================================================================== # Workshop 3F – Focus on Loops # ========================================================================== # print() — Displays an object in the console. print("Hello") # ========================================================================== # Workshop 4 – Vectors III # ========================================================================== # subset() — Selects elements or rows meeting conditions. subset(c(3,7,9), c(3,7,9)>5) # all() — Tests whether all conditions are TRUE. all(c(TRUE,TRUE)) # any() — Tests whether any condition is TRUE. any(c(FALSE,TRUE)) # which() — Returns indices of TRUE values. which(c(2,5,8)>4) # ifelse() — Selects values according to a condition. ifelse(c(2,7)>5,"high","low") # identical() — Checks exact equality of two objects. identical(1:3, c(1L,2L,3L)) # names() — Gets or sets element names. names(c(a=1,b=2)) # barplot() — Draws a bar chart. barplot(c(4,7,2)) # ========================================================================== # Workshop 5 – Matrices and Arrays I # ========================================================================== # matrix() — Creates a two-dimensional matrix. matrix(1:6,nrow=2) # apply() — Applies a function across rows or columns. apply(matrix(1:6,2), 1, sum) # t() — Transposes a matrix. t(matrix(1:6,nrow=2)) # ========================================================================== # Workshop 6 – Matrices and Arrays II # ========================================================================== # rbind() — Joins objects by rows. rbind(c(1,2),c(3,4)) # cbind() — Joins objects by columns. cbind(c(1,2),c(3,4)) # colnames() — Gets or sets column names. colnames(matrix(1:4,2)) <- c("A","B") # rownames() — Gets or sets row names. rownames(matrix(1:4,2)) <- c("X","Y") # array() — Creates a multidimensional array. array(1:8,dim=c(2,2,2)) # ========================================================================== # Workshop 7 – Lists # ========================================================================== # list() — Creates a list of objects. list(name="Jack",age=22) # class() — Reports an object's class. class(list(a=1)) # unlist() — Flattens a list into a vector. unlist(list(a=1,b=2)) # unname() — Removes names from an object. unname(c(a=3,b=4)) # lapply() — Applies a function to each list element. lapply(list(1:3,4:6),sum) # sapply() — Applies a function and simplifies results. sapply(list(1:3,4:6),mean) # ========================================================================== # Workshop 8 – Data Frames # ========================================================================== # data.frame() — Creates a tabular data frame. data.frame(name=c("A","B"),mark=c(70,65)) # read.csv() — Imports data from a CSV file. read.csv("Results.csv",header=TRUE) # complete.cases() — Identifies rows with no missing values. complete.cases(data.frame(a=c(1,NA),b=2:3)) # ========================================================================== # Workshop 9 – Frames, Factors & Tables # ========================================================================== # merge() — Joins data frames using common columns. merge(data.frame(id=1:2,a=3:4),data.frame(id=1:2,b=5:6)) # order() — Returns indices that sort values. order(c(5,1,3)) # tapply() — Applies a function to groups of values. tapply(c(4,5,6),c("A","A","B"),mean) # split() — Splits data into groups. split(1:4,c("A","A","B","B")) # as.data.frame() — Converts an object to a data frame. as.data.frame(matrix(1:4,2)) # table() — Counts occurrences of values or combinations. table(c("A","B","A")) # factor() — Creates a categorical variable. factor(c("urban","rural","urban")) # ========================================================================== # Workshop 19 – Simulation and Visualisation # ========================================================================== # Load ggplot2 before using the functions in this section. library(ggplot2) # set.seed() — Sets the random-number seed for reproducibility. set.seed(42) # aes() — Defines aesthetic mappings for a plot. aes(x=wt,y=mpg) # ggplot() — Initialises a ggplot2 visualisation. ggplot(mtcars,aes(wt,mpg)) + geom_point() # geom_histogram() — Adds a histogram layer. ggplot(mtcars,aes(mpg)) + geom_histogram() # labs() — Sets plot title and axis or legend labels. labs(title="Mileage",x="Weight",y="MPG") # geom_text() — Adds text labels to plotted data. geom_text(aes(label=rownames(mtcars))) # after_stat() — Maps a computed statistic to an aesthetic. aes(y=after_stat(count)) # scale_x_continuous() — Controls a continuous x-axis scale. scale_x_continuous(breaks=seq(1,5,1)) # theme() — Customises non-data plot appearance. theme(legend.position="bottom") # theme_minimal() — Applies a minimal plot theme. theme_minimal() # geom_line() — Adds lines connecting observations. geom_line() # geom_point() — Adds a scatterplot point layer. geom_point() # geom_tile() — Draws rectangular tiles, e.g. a heatmap. geom_tile() # geom_jitter() — Adds points with jitter to reduce overlap. geom_jitter(width=0.1) # ========================================================================== # Workshop 10 – Control Statements I # ========================================================================== # numeric() — Creates a numeric vector, initially zero-filled. numeric(5) # ========================================================================== # Workshop 12 – Functions I # ========================================================================== # paste() — Joins text values into strings. paste("Mean:",mean(1:5)) # return() — Explicitly returns a value from a function. f <- function(x) { return(x*2) }; f(3) # ========================================================================== # Workshop 13 – Functions II # ========================================================================== # unique() — Returns distinct values. unique(c("A","B","A")) # ========================================================================== # Workshop 14 – Functions III # ========================================================================== # as.numeric() — Converts values to numeric form. as.numeric("42") # as.vector() — Converts an object to a vector. as.vector(matrix(1:4,2)) # ========================================================================== # Workshop 15 – Data Analysis I # ========================================================================== # substr() — Extracts or replaces part of a string. substr("10:45",1,2) # ========================================================================== # Workshop 16 – Data Analysis II # ========================================================================== # nchar() — Counts characters in strings. nchar("10:45") # ========================================================================== # Workshop 17 – Data Analysis III # ========================================================================== # median() — Finds the middle value of a distribution. median(c(1,4,8)) # max() — Returns the largest value. max(c(2,5,3)) # min() — Returns the smallest value. min(c(2,5,3)) # range() — Returns the minimum and maximum. range(c(2,5,3)) # which.max() — Returns the index of the first maximum. which.max(c(3,9,4)) # quantile() — Calculates selected distribution quantiles. quantile(1:20,probs=c(.25,.75)) # aggregate() — Summarises data by groups. aggregate(mpg ~ cyl,data=mtcars,FUN=mean) # summary() — Produces a statistical or structural summary. summary(mtcars$mpg) # switch() — Chooses among alternatives by key or position. switch("b",a=1,b=2,c=3) # ========================================================================== # Workshop 18 – Data Analysis IV # ========================================================================== # plot() — Creates a base R plot. plot(mtcars$wt,mtcars$mpg) # cor() — Calculates a correlation coefficient. cor(mtcars$wt,mtcars$mpg,method="pearson") # shapiro.test() — Tests data for normality (Shapiro–Wilk). shapiro.test(rnorm(30)) # boxplot() — Draws box-and-whisker plots. boxplot(mpg ~ cyl,data=mtcars) # t.test() — Performs a Student or Welch t-test. t.test(mpg ~ am,data=mtcars) # aov() — Fits an analysis-of-variance model. aov(mpg ~ factor(cyl),data=mtcars) # TukeyHSD() — Runs Tukey post-hoc pairwise comparisons. TukeyHSD(aov(mpg ~ factor(cyl),data=mtcars)) # Scope and conventions # The source cheat sheet excludes language keywords, operators and # student-defined functions. Each listed function appears only once. # ggplot2 geoms and themes can be added to a ggplot object with +.