Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 17 total  RSS 

Create data frame from variable number of vectors

// Create a data frame from a varied number of vectors
// Taken from http://article.gmane.org/gmane.comp.lang.r.general/56501/match=create+data+frame

N1 <-c(1,2,3,4)
N2 <-c(1,2,3,4)
N3 <-c(1,2,3,4)
abc <-c(1,2,3)
lab <- paste("N", seq(along=abc), sep="")
D <- data.frame(lapply(lab, get))
names(D) <- lab

Call Growl from R

// Send an alert to growl with the R.app icon.
// Useful for indicating the end of a long simulation.

system(paste("growlnotify -a R -t \"Message\" -m", message, sep=""))

Run R from the command line

// This runs R from the command line in batch mode.
// The log file is output to track R's progress

R CMD BATCH --vanilla path/to/file.R file.log &

Iteratively create objects

// Iteratively create objects from a list of names.
// Especially useful for creating consistent model objects for a list of data sources.
// Wrapping the assign statement in a try block is often advisable.

for(item in itemList){
	assign(paste(item, "object", sep="."),  function(get(paste(item, "data", sep=".")), options)
}

clear workspace

clean up R workspace

rm(list = ls(all = TRUE))

Position-based substitution in arrays

// Replace array values based on their row and column position
// This is an alternative to using for loops to test each position

a <- array(0, dim=c(10, 10))
a[row(a) <= col(a)*2] <- 1

Zero-inflated negative binomial

// Simulates a zero-inflated, negative binomial
// from Ben Bolker

rzinbinom <- function(n, mu, size, zprob) {
  ifelse(runif(n) < zprob, 0, rnbinom(n, mu=mu, size=size))
}

Spotlight queries of R documentation

// from http://comments.gmane.org/gmane.comp.lang.r.mac/642
// Use Spotlight to query R documentation

spotlight<-function(word) {
place<-paste(Sys.getenv("R_HOME"),"/library/",sep="")
string<-paste("mdfind -onlyin",place,word,"|",getOption("pager"))
system(string, intern=TRUE)
}

Read CSV and plot



oaks <- read.table("assign1/oaksdf.csv",sep=",")
oakpts <- as.points(oaks[,1],oaks[,2])
plot(oakpts)

create rotated axis labels

The R FAQ states:

par(mar = c(7, 4, 4, 2) + 0.1)
plot(1 : 30, xaxt = "n",  xlab = "")
labels <- paste("Label", 1:30, sep = " ")
text(1:30, par("usr")[3] - 0.25, srt = 90, adj = 1,labels = labels, xpd = TRUE)
mtext(1, text = "X Axis Label", line = 6)


Also see Figure 1 and associated code in Paul Murrell (2003), “Integrating grid Graphics Output with Base Graphics Output�, R News, 3/2, 7–12.
« Newer Snippets
Older Snippets »
Showing 1-10 of 17 total  RSS