Skip to content

Instantly share code, notes, and snippets.

@drewhendrickson
Last active December 27, 2015 10:59
Show Gist options
  • Select an option

  • Save drewhendrickson/7315518 to your computer and use it in GitHub Desktop.

Select an option

Save drewhendrickson/7315518 to your computer and use it in GitHub Desktop.
Snippits of R code
# without
"%w/o%" <- function(x, y) x[!x %in% y]
# when an error occurs, invoke debug mode
options(error = browser)
# an R array produces a 1D JS array
# an R list containing JS arrays (strings) produces a 2D JS array
write.js.array <- function(l) {
out <- "["
for (i in l) {
out <- paste(out, i, ", ", sep="")
}
# add ] at end
substring(out, nchar(out) - 1) <- "]"
# remove final space
out <- substr(out, 1, nchar(out)-1)
return(out)
}
# takes a data frame
# first column contains all of the keys
# second column contains all of the values
write.js.assoc.array <- function(name, df) {
output <- paste("var", name, "= {")
for (i in unique(df[,1])) {
output <- paste(output, i, " : ", write.js.array(df[df[,1] == i,2]), ", ", sep="")
}
# add } at end
substring(output, nchar(output) - 1) <- "}"
# add ; at end
substring(output, nchar(output)) <- ";"
return(output)
}
unique_in_list <- function (l1, l2) {
return (l1[!(l1 %in% l2)])
}
# knit all Rmd files in a folder
files <- list.files(path=".", pattern="*Rmd$")
library(knitr);
for (f in files) {
knit(f)
}
# run linear regression separately for multiple levels
lapply(1:3, function(index) summary(lm(y~age, data=racedata[racedata$race==index,])))
# create a new column in data frame for each existing column
jan <- rnorm(100, 3, 5)
feb <- rnorm(100, 4, 8)
march <- rnorm(100, 2, 5)
months <- as.data.frame(cbind(jan, feb, march))
for (n in names(months)) {
months[[paste0("HadInc_", n)]] <- as.numeric(months[[n]] > 0)
}
head(months)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment