在二维网格上计算/绘制统计数据
假设我有一个 R 数据框,其中的列指定个人的位置(纬度/经度)、身高和性别:
x <- data.frame(
lat=c(39.5,39.51,38,38.1,38.2),
long=c(86,86,87,87,87),
gender=c("M","F","F","M","F"),
height=c(72,60,61,70,80)
)
我想将数据分成二维(例如,放入 1000m x 1000m 的正方形)并计算以下内容(然后显示在地图):
- 每个箱中女性的百分比是多少
- 每个箱中男性的平均身高是多少
如果可能的话我想使用ggplot2。
Suppose I have an R data frame with columns that specify location (lat/long), height, and gender of individuals:
x <- data.frame(
lat=c(39.5,39.51,38,38.1,38.2),
long=c(86,86,87,87,87),
gender=c("M","F","F","M","F"),
height=c(72,60,61,70,80)
)
I want to bin the data in two dimensions (e.g. into 1000m x 1000m squares) and compute the following (then display on a map):
- What percentage of individuals in each bin are female
- What is the average height of males in each bin
If possible I'd like to use ggplot2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅 cut 函数,了解从纬度/经度转换为 bin 的方法(另请参阅 cut 帮助中的“另请参阅”部分以了解其他选项)。假设矩形网格足够好,如果该区域足够大以使地球曲率影响事物,您将需要查看空间包。
然后使用 tapply 或 plyr 包来计算网格每个单元格内的摘要。
现在按照您想要的方式绘制结果。
See the cut function for a way to convert from lat/lon to bins (also look at the see also section of the help on cut for other options). This assumes that a rectangular grid is good enough, you will need to look at the spatial packages if the area is big enough for the curvature of Earth to affect things.
Then use tapply or the plyr package to compute your summaries within each cell of the grid.
Now plot the results however you want.