【问题标题】:Error when working with spatial data in R在 R 中处理空间数据时出错
【发布时间】:2012-08-04 19:54:59
【问题描述】:

在尝试处理我似乎无法调试的数据时,我遇到了几个错误。

这是 R 脚本https://dl.dropbox.com/u/28231177/This%20Should%20Work.R
这是数据https://dl.dropbox.com/u/28231177/my_data.csv

这是我运行它们时包含错误的最后几行:

pds <- fortify(sf_map)
# Using OBJECTID to define regions.
pds$OBJECTID <- as.integer(pds$OBJECTID)
# Error in `$<-.data.frame`(`*tmp*`, "OBJECTID", value = integer(0)) : 
# replacement has 0 rows, data has 16249


### Make the map

p1 <- ggplot(my_data, aes(map_id = zip))
p1 <- p1 + geom_map(aes(fill=vol, map_id = zip), map = pds)
p1 <- p1 + expand_limits(x = pds$lon, y = pds$lat) + coord_equal()
p1 + xlab("Basic Map with Default Elements")
# Error in unit(x, default.units) : 'x' and 'units' must have length > 0

【问题讨论】:

  • 另外,这里是 shapefile dl.dropbox.com/u/28231177/sfzipcodes.zip
  • 什么是名称(pds)?我敢说 OBJECTID 不是其中之一。 pds$OBJECTID
  • @mdsumner,这就是我得到的:pds &lt;- fortify(sf_map) # Using OBJECTID to define regions. names(pds) #[1] "long" "lat" "order" "hole" "piece" "group" "id" 看起来你是对的。那应该设置到哪一列?身份证?
  • 我将 OBJECTID 更改为 id 并且没有看到第一个错误 ("Error in $&lt;-.data.frame...)。我仍然收到第二个空白图错误:(
  • 试试不长,调试很无聊,但要注意,不会花很长时间

标签: r csv import-from-csv


【解决方案1】:

如果你设置,你的代码对我有用

pds <- fortify(sf_map, region = "ID") 

删除线

pds$OBJECTID <- as.integer(pds$OBJECTID)

你也应该使用long 而不是@mdsumner 提到的lon

这里有一个稍微不同的解决方案(使用geom_polygon 而不是geom_map

library(maptools)
library(ggplot2)

## 'fortify' needs 'library(gpclib)' locally available
gpclibPermit()

## Import the shapefile
sf_map <- readShapeSpatial("sfzipcodes", ID = "ID")

## Import the data
my_data <- read.csv("my_data.csv")
my_data <- unique(my_data)

## Merge the data
sf_df <- fortify(sf_map, region='ID')
sf_df <- merge(sf_df, my_data, by.x="id", by.y="zip", all=FALSE)
sf_df <- sf_df[order(sf_df$group, sf_df$order), ]

## Make the map
p2 <- ggplot(sf_df, aes(x=long, y=lat, group=group, fill=vol))
p2 <- p2 + geom_polygon() + coord_equal()
p2 <- p2 + xlab("Basic Map with Default Elements")
p2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    相关资源
    最近更新 更多