Sunday, January 9, 2011

Some useful R functions

Its been a while. In that time there have been several instances when I've been in need of some of the following functions and I had to go digging through my old homeworks to find specific instances when I used them; so I thought they'd be worth posting on here.

First the proc.time() function is useful to see the runtime of a program. Here's an example that will give the run time in seconds:

time <- proc.time()
# - run some function - #
proc.time()[3] - time[3]

Some of the functions that I wrote for missing data have proven to be quite useful as well. First I always forget the function and often confuse complete.cases with na.omit

### Ways to find what values are missing
complete.cases(sed) #T/F if row has any missing
na.omit(sed) #gives only rows with no missing values #have to use as a logical argument, not ==NA

Here are some functions that I think are quite useful and I am surprised they aren't available in R, or if they are, I don't know what they are called

### Identify cols that are entirely NA
NA.cols<-function(X) {
 cols<-apply(X,2,function(x) sum(
 if(length(na.cols)==0) na.cols<-'Each column has at least one non NA value'

### Identify rows that are entirely NA (opposite of
### complete.cases)
NA.rows<-function(X) {
 rows<-apply(X,1,function(x) sum(
 if(length(na.rows)==0) na.rows<-'Each row has at least one non NA value'

### Identify cols that have no have no NA values (I guess you
### could also transpose the data and do na.omit)
complete.cols<-function(X) {
 cols<-apply(X,2,function(x) sum(
 if(length(complete.cols)==0) complete.cols<-'There are no complete variables'

I also have my simple imputation function. For real imputation techniques I recommend the Amelia package (at least thats what I used for the multivariate class, and it seemed to have some nice features).  I found using proc.time() that it takes like 22 seconds to run on my machine, mostly because the 'hot deck' imputation could probably be more efficient. The real lesson here is that when you write a function, you get to name it after yourself

### A function that returns some simple imputation methods
Alan.imputations<-function(X) {



 for(j in 1:ncol(X)) {
  if(is.numeric(X[,j])==T) {
 for(j in 1:ncol(X)) {

 cols<-apply(X,2,function(x) sum(
 for(i in 1:ncol(comp.X)) { 
  numeric.cols[i] <- is.numeric(comp.X[,i])
 sX <- scale(< - matrix(attr(sX,"scaled:center"),nrow(,ncol(,byrow=T)<,"scaled:scale"),nrow(,ncol(,byrow=T)<-NA.cols(<[,]

 for(i in 1:nrow( {

 for(i in 1:nrow(dist)) {
 if(complete.cases([i]==F) {
   while(sum([min,[i,])]))!=0) {


 alan<-list(max=X.max, mean=X.mean, median=X.median, min=X.min, sample=X.sample,, hotdeck=X.hotdeck)

(note that some of the spacing gets messed up, just in case something doesn't run right)