My cheat sheet on R

From HolsingerLabWiki
Jump to: navigation, search

Contents

Libraries

Removing a library

Sometimes when you've finished working with a library, you'd like to remove it from memory without leaving R and starting it over again. It's very easy with detach(). For example,

detach(package:lme4)

removes lme4.

Input

Use a Google spreadsheet as input

It's easy to use read.csv() or read.data() to read a file on a local hard drive, but suppose you want to share data with others and work on the same file. Use GoogleDocs. This post at Revolutions explains how.

Output

Putting a table into LaTeX

library(xtable)
result <- replicate(6, rnorm(10)) # random matrix
print(xtable(result), type="latex", file="output.tex")

From tom at LaTeX Matters

Manipulating data

Drop unused levels from all factors in a data frame

## Drop unused factor levels from all factors in a data.frame
## Author: Kevin Wright.  Idea by Brian Ripley.
##
drop.levels <- function(dat) {
  dat[] <- lapply(dat, function(x) x[,drop=TRUE])
  return(dat)
}

Graphics

Putting log-scale on x- and y-axes

From a data frame merged with columns SLA, Amax, and species (as a factor)

with(merged, plot(SLA, Amax, xlab="SLA", ylab="Amax", log="xy", pch=as.numeric(species)+15))

The "+15" on pch gives symbols that are easier to read. It starts with a filled circle instead of an open circle. For a log-scale on the x-axis only use log="x". For a log-scale on the y-axis only use log="y"

File management

Copy all files from one directory to another

file.copy(list.files(source), destination)

From Adam

Development

Integrating C++ and R

Packages

Examples of Rcpp

Personal tools