TransWikia.com

In R, abstract data from SpatialPolygonsDataFrame but got NA

Geographic Information Systems Asked on December 6, 2020

I tried to extract data from a SpatialPolygonsDataFrame, but got all NA.

 slot(nc,"data")[c("Northampton","Clay","Macon","Graham","Yancey","Mitchell","Avery"),]

The data show as:

     SP_ID CNTY_ID east north L_id M_id names AREA PERIMETER CNTY_ NAME FIPS
NA    <NA>      NA   NA    NA   NA   NA  <NA>   NA        NA    NA <NA> <NA>
NA.1  <NA>      NA   NA    NA   NA   NA  <NA>   NA        NA    NA <NA> <NA>
NA.2  <NA>      NA   NA    NA   NA   NA  <NA>   NA        NA    NA <NA> <NA>
NA.3  <NA>      NA   NA    NA   NA   NA  <NA>   NA        NA    NA <NA> <NA>
NA.4  <NA>      NA   NA    NA   NA   NA  <NA>   NA        NA    NA <NA> <NA>
NA.5  <NA>      NA   NA    NA   NA   NA  <NA>   NA        NA    NA <NA> <NA>
NA.6  <NA>      NA   NA    NA   NA   NA  <NA>   NA        NA    NA <NA> <NA>

Can anyone tell me what I should do?

One Answer

Indexing like this:

slot(nc,"data")[c("Northampton","Clay","Macon","Graham","Yancey","Mitchell","Avery"),]

works if your data has "row names":

> d = data.frame(x=1:5, y=runif(5))
> d
  x         y
1 1 0.4038795
2 2 0.9389338
3 3 0.3739626
4 4 0.1563043
5 5 0.1237213
> rownames(d)=LETTERS[1:5]
> d
  x         y
A 1 0.4038795
B 2 0.9389338
C 3 0.3739626
D 4 0.1563043
E 5 0.1237213
> d[c("A","E"),]
  x         y
A 1 0.4038795
E 5 0.1237213

row names are optional, and if you don't have row names, you get NA NA NA...

> d = data.frame(x=1:5, y=runif(5))
> d[c("A","E"),]
      x  y
NA   NA NA
NA.1 NA NA

If those names are actually in a column, then match them this way:

> d = data.frame(x=1:5, y=runif(5), z=LETTERS[1:5])
> d
  x         y z
1 1 0.2858429 A
2 2 0.9910520 B
3 3 0.7079778 C
4 4 0.0564100 D
5 5 0.7169663 E
> d[d$z %in% c("A","E"),]
  x         y z
1 1 0.2858429 A
5 5 0.7169663 E

Answered by Spacedman on December 6, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP