R Cookbook

General

# assign something
x <- 1

# print something
x

# list objects in workspace
ls()

Atoms

# a character atom
x <- "text"

# a numeric atom
y <- 2

# a missing value
z <- NA

Vectors

# build vectors manually
x <- c(1,2,3)
y <- c("a","b","c")

# build from vectors or atoms
xx <- c(x,x)
z <- c(x,1)

# find the length of a vector
length(z)

# pull out the second element of a vector
z[2]
a <- z[2]

# get summary statistics
summary(z)

Data Frames

# build data frame from vectors
id <- c("A","B","C")
exposure <- c("low","med","high")
outcome <- c(0,0,1)
study <- data.frame(id,exposure,outcome)

# inspect first few rows of data frame
head(study)

# print the vector of names
names(study)

# rename second variable
names(study)[2] <- “exp”