[R] How to bin x,y,z vectors into matrix?
Sarah Goslee
sarah.goslee at gmail.com
Sat Jul 19 18:31:39 CEST 2014
Hi Mark,
First you need to use cut() to bin the values. Here's an example:
# generate some fake data
temp <- data.frame(x=runif(20), y=runif(20), z=runif(20))
# bin x and y
temp$x <- cut(temp$x, seq(0, 1, by=.2))
temp$y <- cut(temp$y, seq(0, 1, by=.2))
>From there, there are all sorts of ways to get your desired table. Here are two:
xtabs(z ~ x + y, data=aggregate(z ~ x + y, data=temp, FUN="mean"))
or
library(ecodist)
with(temp, crosstab(x, y, z, "mean"))
On Sat, Jul 19, 2014 at 10: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.
Using the targeted www.rseek.org search engine is a whole lot more
effective than using base Google for R searches.
Sarah
> 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
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list