Skip to content

Instantly share code, notes, and snippets.

@danielecook
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielecook/8809319 to your computer and use it in GitHub Desktop.
Save danielecook/8809319 to your computer and use it in GitHub Desktop.
A list of helper functions in R
# I am trying to make R a little easier by adding a few helper functions. Most of these mimic functionality seen in Stata.
# This function attempts to mimic the order command in Stata;
# Usage:
# df <- corder(df,<list of columns>)
# Order variables in a data frame.
corder <- function(df,...) {
cols <-as.vector(eval(substitute((alist(...)))),mode="character")
stopifnot(is.data.frame(df))
df[,c(cols,unlist(setdiff(names(df),cols)))]
}
# Drop Variables from a data frame.
# Usage:
# df <- cdrop(df, <list of vars to drop>)
cdrop <- function(df, ...) {
cols <-as.vector(eval(substitute((alist(...)))),mode="character")
stopifnot(is.data.frame(df))
df[,c(unlist(setdiff(names(df),cols)))]
}
# Preview a data frame in Excel [Only works on Mac]
excel <- function(df) {
f <- paste0(tempdir(),'/', make.names(deparse(substitute(df))),'.',paste0(sample(letters)[1:5],collapse=""), '.csv')
write.csv(df,f)
system(sprintf("open -a 'Microsoft Excel' %s",f))
}
pp <- function(header = TRUE, ...) {
# Taken from the psych package; Thank you William Revelle!
# Type pp() to fetch data from the clipboard.
MAC <- Sys.info()[1] == "Darwin"
if (!MAC) {
if (header)
return(read.table(file("clipboard"), header = TRUE,
...))
else return(read.table(file("clipboard"), ...))
}
else {
if (header) {
return(read.table(pipe("pbpaste"), header = TRUE,
...))
}
else {
return(read.table(pipe("pbpaste"), ...))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment