[R] How to bin x,y,z vectors into matrix?

William Dunlap wdunlap at tibco.com
Sat Jul 19 18:41:53 CEST 2014


You could use tapply() and cut() in base R, as in
> tapply(d$z, INDEX=list(y=cut(d$y,breaks=seq(900,1300,by=100)), x=cut(d$x,breaks=seq(35,60,by=5))), FUN=mean)
                   x
y                    (35,40]  (40,45] (45,50]  (50,55]  (55,60]
  (900,1e+03]       1644.779 1643.957      NA       NA       NA
  (1e+03,1.1e+03]         NA       NA      NA 1597.028       NA
  (1.1e+03,1.2e+03]       NA       NA      NA 1281.988 1846.123
  (1.2e+03,1.3e+03]       NA       NA      NA 1990.707       NA

cut() does the binning and tapply() applies the function 'FUN' to each group.

Bill Dunlap
TIBCO Software
wdunlap tibco.com


On Sat, Jul 19, 2014 at 7:57 AM, Mark Miller <mamillerpa at gmail.com> wrote:
> This is probably a basic question, but I haven't been able to Google
> anything helpful after trying for days.
>
> I have an R dataframe with x,y,z tuples, where z is a response to x and y
> and can be modeled as a surface.
>
>     > head(temp)
>              x         y        z
>     1 36.55411  965.7779 1644.779
>     2 42.36912  978.9721 1643.957
>     3 58.34699 1183.7426 1846.123
>     4 53.55439 1232.2696 1990.707
>     5 50.76167 1115.2049 1281.988
>     6 51.37299 1059.9088 1597.028
>
> I would like to create a matrix of mean z values, with rows representing
> binned y values and columns representing binned x values, like
>
>                            0<x<40    40<x<60  60<x<80   x>80
>           0<y<800   1000.0    1100.00  1100.00   1000.0
>       800<y<1200 1000.0    1200.00  1200.00   1000.0
>     1200<y<1400 1000.0    1200.00  1200.00   1000.0
>               y<1400 1000.0    1100.00  1100.00   1000.0
> thanks
> Mark
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list