Zelig For R Cheat Sheet: Plots Vectors

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Zelig for R Cheat Sheet Plots to screen by default.

Plots to screen by default. Let x and y be vectors of length n Vectors: 1D arrays with undefined length.
Scatterplot plot(x, y) Vector (undefined type/length) var <- array()
Line plot plot(x, y, type = "l") Integer vector var <- 10:20
Launch R Add points points(x, y) Numerical vector var <- c(2, 13, 44)
Add a line lines(x, y) Numerical vector var <- seq(5, 10, by = 0.5)
GUI (Windows or RAqua) Double-click icon
Histogram hist(x) Character vector var <- rep("file", 15)
ESS within XEmacs M-x R (Esc, then x, then R)
Kernel density plot plot(density(x)) Use c() and rep() with numeric, character, and logical values.
Terminal R
Contour plot contour(x, y)
To quit, type q().
To generate a logical vector (TRUE/FALSE), use logical operators
Plot options Separate options with commas: compare two vectors of the same length:
Installing Zelig Within R, type: Title main = "My Title" var1 <- c(1, 3, 5, 7, 9); var2 <- c(1, 2, 3, 4, 5)
source("http://gking.harvard.edu/zelig/install.R") X-axis label xlab = "Independent Var" logical <- var1 == var2
Y-axis label ylab = "Dependent Var" Use logical vectors to recode other vectors or matricies. Putting a
Loading Zelig Within R, type: library(Zelig) X-axis limits xlim = c(0, 10) logical statement in square brackets extracts only those elements
Y-axis limits ylim = c(0, 1) for which the logical statment is TRUE:
Colors color = "red" or color = c("red", "blue") var3 <- var1[logical] or var3 <- var1[var1 == var2]
Syntax R is case-sensitive!
Default R prompt > Saving plots Export plots as .pdf or .eps files A factor vector is a special vector that separates each unique
Execute a command Press Return or Enter Call the file to which you will store the plot: value of the vector into either indicator variables (for unordered
Comment rest of line # ◦ For .eps files: factors) or a Helmert contrast matrix (for ordered factors) in
Store objects <- ps.options(family = c("Times"), pointsize = 12) regression functions.
Separate arguments for functions , postscript(file = "mygraph.eps", horizontal = FALSE,
paper = "special", width = 6.25, height = 4)
◦ For .pdf files:
Matricies and arrays 2+D arrays have fixed dimensions.
Saving objects to disk To the working directory: Create a matrix mat <- matrix(NA, nrow = 5, ncol = 5)
pdf(file = "mygraph.pdf", width = 6.25, height = 4,
Save objects save(x1, x2, file = "object.RData") mat <- cbind(v1, v2)
family = "Times", pointsize = 12)
Save workspace save.image() mat <- rbind(v1, v2)
Draw your plot (it won’t display to screen).
Save workspace to file save.image(file = "May21.RData") Create an array arr <- array(NA, dim = c(3, 2, 1),
Close and save the file using dev.off().
dimnames = list(NULL, NULL, "x1"))
Common commands Math operations + - \ * Extracting or recoding elements in a matrix or array:
For vectors or arrays of the same dimension, R performs math Row in a matrix mat[5, ]
List objects in workspace ls() operations on each (i) or (i, j) or (i, j, . . . , n) element with its Column in a matrix mat[ , 5]
Remomve objects from workspacs remove(x1, x2) corresponding element in the other vector or array. 3rd dimension in a 4D array arr[ , , 5, ]
Length of a vector length(x)
Dimensions of a matrix or array dim(x) Matrix operations
Names for lists or data frames names(x) Lists A list can contain scalars, matricies, and arrays of
Transpose t(P)
Type of object class(x) different types (numeric, logical, factor, and character) at the
Inverse solve(P)
Summary (for most things) summary(x) same time. Lists have a flexible number of elements and can be
Matrix multiplication P %*% Q
Cross tab tabular(x) enlarged on the fly.
Loading packages library(PACKAGE) Data structures (or R objects) Create a list ll <- list(a = 5, b = c("in", "out"))
Quitting R q() ll <- list(); ll$a <- 5
Batch mode source("myfile.R") R stores all objects in the workspace (or RAM). You can store all Extract list elements ll[[6]]
types of objects – at the same time. ll$a
Logical operators Remove list elements ll[[6]] <- NULL
Scalars Store a scalar value using <- (e.g., a <- 5) ll$a <- NULL
Exactly equals == Numeric 1, 3.1416, NA, NaN, -Inf, Inf
Not equal != Logical TRUE, FALSE
Character "Alpha", "beta" Data Frames A data frame is a list in which every list
Greater than > element has the same length or number of observations. Like a
Greater than or equal >= (Character values are always enclosed in quotes.)
list, each element can be of a different class. Use list or matrix
Less than < operations on a data frame. For a data frame data:
Less than or equal <= Arrays
View the 5th row data[5,]
And & An array can have one dimension (a vector), two dimensions (a Extract the 7th variable data[[7]]
Or | matrix), or n > 2 dimensions. Arrays hold one type of scalar Extract the age variable data$age
(Note: = is not a logical operator!) value. Insert a new variable data$new <- new.var
Delimiters Verifying data integrity Binomial
The data object is an R data.frame, with special properties: CDF dbinom(x, size, prob)
Functions you use ( ) PDF pbinom(q, size, prob)
Functions you write { } ◦ Each variable (column) has a name:
• To view names: names(data) Quantiles qbinom(p, size, prob)
N-dimensional arrays N = 1: [ ] Random Draws rbinom(n, size, prob)
N = 2: [ , ] • If names are missing or incorrect, assign correct names
N = 3: [ , , ] names(data) <- c("Y", "X") Beta
Lists $ or [[ ]] ◦ Observations (rows) may have a name: CDF dbeta(x, shape1, shape2)
• To view names: rownames(data) PDF pbeta(q, shape1, shape2)
• If names are missing or incorrect, assign correct names Quantiles qbeta(p, shape1, shape2)
Loading data rownames(data) <- 1:nrow(data) Random Draws rbeta(n, shape1, shape2)
◦ Display the 5th row: data[5,]
Change directories (using setwd()) to the directory that contains ◦ Display the variable Y: data$Y Poisson
your data files before attempting to read data into R! ◦ Display a summary of the entire data frame: summary(data) CDF dpois(x, size, prob)
Space- or tab-delimited data <- read.table("data.tab") PDF ppois(q, size, prob)
Comma-separated values data <- read.csv("data.csv") Distributions Quantiles qpois(p, size, prob)
Stata .dta file library(foreign) Random Draws rpois(n, size, prob)
data <- read.dta("data.dta") For all distribtions, let
SPSS .sav file library(foreign) x, q be vectors of quantiles Gamma
data <- read.spss("data.sav", p be a vector of probabilities CDF dgamma(x, shape, rate = 1, scale = 1/rate)
to.data.frame = TRUE) n be a scalar (the number of random draws). PDF pgamma(q, shape, rate = 1, scale = 1/rate)
Quantiles qgamma(p, shape, rate = 1, scale = 1/rate)
Uniform Random Draws rgamma(n, shape, rate = 1, scale = 1/rate)
Options for loading data
CDF dunif(x, min = 0, max = 1) Normal
◦ First row = variable names: PDF punif(q, min = 0, max = 1) CDF dnorm(x, mean = 0, sd = 1)
data <- read.table("data.tab", header = TRUE) Quantiles qunif(p, min = 0, max = 1) PDF pnorm(q, mean = 0, sd = 1)
◦ Missing values = −9 (for example) Random Draws runif(n, min = 0, max = 1) Quantiles qnorm(p, mean = 0, sd = 1)
data <- read.table("data.tab", na.strings = "-9") Random Draws rnorm(n, mean = 0, sd = 1)
(Recodes missing values as R NA values.) Bernoulli
Copyright °c 2006 Olivia Lau
(You can combine both options.) Same as Binomial with size = 1. http://www.people.fas.harvard.edu/~olau/computing/Rtips.pdf

You might also like