Box Me

November 8, 2013
By

(This article was first published on Drunks&Lampposts » R, and kindly contributed to R-bloggers)

Here’s a short R function I wrote to turn a long data set into a wide one for viewing. It’s not the most exciting function ever but I find it quite useful when my screen is wide and short. It simply cuts the data set horizontally into equal size pieces and puts them side by side. Lazy I know!


#'boxMe
#'
#'Turns an overly long data frame into something easier to look at
#'
#' @param d A dataframe or matrix
#' @param nrow The number of rows you would like to see in the new dataframe
#' @examples
#' test.set<-data.frame(x=rnorm(100), y=rnorm(100))
#' boxMe(test.set, 18)
#' 
#' library(ggplot2)
#' boxMe(diamonds, 10)


boxMe<-function(d, nrow){
  
  # Number of rows and columns
  r<-dim(d)[1]
  c<-dim(d)[2]
  
  rem<-r %% nrow # Number of blank rows
  reps<-floor(r/nrow) # Number of folds
  s<-seq(1, reps*nrow, by=nrow) # Breaks
  
  box<-d[1:nrow,] # First col
  
  for (i in s[-1]){

    ap<-d[i:(i+nrow-1),]
    box<-cbind(box, ap)
    
  }
  
  #Append remainder
  
  if (rem>0){
  
    n.null.rows<-nrow-rem
    rem.rows<-d[(reps*nrow+1):r,]
    null.block<-as.data.frame(matrix(rep(NA, (n.null.rows*c)), nrow=n.null.rows))
    names(null.block)<-names(rem.rows)
    last.block<-rbind(rem.rows, null.block)
    box<-cbind(box, last.block)
  
  }

  return(box)

}

To leave a comment for the author, please follow the link and comment on their blog: Drunks&Lampposts » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Mango solutions



RStudio homepage



Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training

datasociety

http://www.eoda.de





ODSC

ODSC

CRC R books series





Six Sigma Online Training









Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)