danielecook
2/4/2014 - 6:21 PM

A list of helper functions in R

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"), ...))
        }
    }
}