问题
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
回答1:
You could use tapply
and cut
here
with(temp, tapply(z,
list(
y=cut(y, breaks=c(0,800,1200,1400,Inf), include.lowest=T),
x=cut(x, breaks=c(0,40,60,80,Inf), include.lowest=T)
),
mean)
)
The cut
function splits x
and y
into what ever groups you like. While tapply
calculates the mean
here for each grouping of the those values in the list.
# x
# y (0,40] (40,60] (60,80] (80,Inf]
# (0,800] NA NA NA NA
# (800,1.2e+03] 1644.779 1592.274 NA NA
# (1.2e+03,1.4e+03] NA 1990.707 NA NA
# (1.4e+03,Inf] NA NA NA NA
来源:https://stackoverflow.com/questions/24841888/how-to-bin-x-y-z-vectors-into-matrix-r