[R] Kind of 2 dim histogram - levelplot

Hans-Peter gchappi at gmail.com
Tue Jul 5 11:03:24 CEST 2005


Dear R-List,

I've written some code to put measurement values at a position x and y
in bins (xb and yb). It works, but I wonder if there isn't a function
that would do what I do by hand in "# fill data in bins"?

Here is the code:

  # data
x <- c( 1.1, 1.5, 2.3, 2.5, 2.6, 2.9, 3.3, 3.5 )
y <- c( 6.3, 6.2, 5.9, 5.3, 5.4, 4.2, 4.8, 4.6 )
val <- c( 50,  58,  32,  14,  12,  17,  36,  52 )
  # bins
xb <- 1:4
yb <- 4:7
xble <- length( xb ) - 1
yble <- length( yb ) - 1
  # fill data in bins
g <- expand.grid( x=xb[1:xble], y=yb[1:yble] )
g$cnt <- numeric( dim( g )[1] )
g$avg <- numeric( dim( g )[1] )
g$proz <- numeric( dim( g )[1] )

idx <- 1
for (myy in 1:yble) {
  for (myx in 1:xble) {
    xIdx <- which( ( (x >= xb[myx]) & (x < xb[myx + 1]) ) )
    yIdx <- which( ( (y >= yb[myy]) & (y < yb[myy + 1]) ) )
    bIdx <- intersect( xIdx, yIdx )
    g[idx,3] <- length( bIdx )
    g[idx,4] <- sum( val[bIdx] )/g[idx,3]
    g[idx,5] <- sum(val[bIdx]>0)/length(bIdx)*100
    idx <- idx + 1
  }
}
  # show data and plot
g
levelplot(cnt ~ x*y, g, main = "Count", region = TRUE)


Best regards,
Hans-Peter




More information about the R-help mailing list