bin <- function(x, nbin=1, exact=FALSE) { # # Fuction to bin data in x by nbins. # If exact is true, then the input vector must contain an integral number # of bins. Otherwise, the end is binned as much as possible but will # contain fewer data points than the first bins. # # AH 3/2007 # if ((nbin%%1)!= 0 || (nbin <= 0)!= 0) stop("Binning by positive integers only") lenx <- length(x) if (nbin > lenx) stop("Bin size longer than data; use mean") nextra <- length(x)%%nbin numbins <- (lenx-nextra)/nbin b <- real(length=numbins) # set up binned results vector if (nextra != 0) { b <- real(length=numbins+1) # set up binned results vector if (exact == TRUE) stop("Nonintegral number of bins in output") } nstart <- 1 # loop through array to produce binned version bmean for(i in 1:numbins) { nend <- nstart+nbin-1 b[i] <- mean(x[nstart:nend]) nstart <- nend+1 } if (nextra != 0) b[i+1] = mean(x[nstart:lenx]) return(b) }