0

I am trying to convert two columns of data, lat and long coordinates, from dd to dms using;

dd2dms(y, NS = TRUE)

but when I do get the error

Error in Math.factor(dd) : sign not meaningful for factors

I know there are good answers out there to help with converting to different types of data, like here. Unfortunately however, this does not solve my problem because my data is in fact, numerical.

My data is coming from the US Census Bureau shapefiles available here. This is the code I am using.

require(rgdal)
UAP=readOGR(dsn = "C:/Directory", layer = "file")

The columns I want to convert look like this

 INTPTLAT10   INTPTLON10
+40.7185358 -084.0757264
+40.7038198 -084.1723263

So first I try:

> y = UAP@data$INTPTLAT10
> sapply(y, mode)
[1] "numeric" "numeric" "numeric" "numeric" #etc...
> dd2dms(y)
Error in Math.factor(dd) : sign not meaningful for factors

I tried a couple other simple tests to try and diagnose where my problem was.

> x=UAP@data[14]
> sapply(x, mode)
INTPTLAT10 
 "numeric"
> dd2dms(x, NS = TRUE)
Error in Math.data.frame(dd) : 
  non-numeric variable in data frame: INTPTLAT10

>x = +40.5987
>sapply(x)
[1] "numeric"
>dd2dms(x, NS = TRUE)
[1] 40d35'55.32"N

I need to get these coordinates into DMS so that I can apply the distance formula (which requires the use of trig functions so they must be in DMS format). But I am confused about where this error is popping up from.

Any help would be appreciated! I have been struggling with this for days!

Community
  • 1
  • 1
Dan Johnson
  • 77
  • 1
  • 7
  • 1
    I suspicious that the unreferenced package from which you are getting `readOGR` keeps coordinates in factor class so that the "plus-signs" will display as a geographer would expect. (Minus signs would display properly if stored as numeric.) `mode` is less informative than `class` in such an instance. – IRTFM Jun 07 '13 at 14:23
  • Thank @DWin, I just included the package that I used for the readOGR command. – Dan Johnson Jun 10 '13 at 06:18

2 Answers2

0

Your data might have some non-numeric entries buried somewhere, eg strings like "NA" or whatever. When R sees them, it assumes the whole column is character, which is probably then being converted into a factor.

Note that:

  • mode(f) for a factor f is numeric (since factors are internally stored as numbers). You want class(f).

  • if x is a primitive vector, then sapply(x, mode) is needlessly complex. You want just mode(x).

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
0

What you're missing is that y is probably a factor, as Hong Ooi implied. Example:

Rgames> foo<-as.factor(1:5)
Rgames> mode(foo)
[1] "numeric"
Rgames> class(foo)
[1] "factor"

So convert, e.g. as yy <- as.numeric(as.character(y)) and you should be OK.

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73