-1

I have a data frame with 'lat', 'lon' values such as:

  index      lat         lon     
 ------- ----------- ----------- 
      1   51.513393   -0.115650  
      2   51.513428   -0.115461  
      3   51.513428   -0.115462  
      4   51.513428   -0.115465  
      5   51.513428   -0.115470  
      6   51.513432   -0.115462  
      7   51.513432   -0.115467  
      8   51.513435   -0.115471  
      9   51.513439   -0.115468  
     10   51.513439   -0.115469  

I'm trying to obtain the centre of these points:

center_point <- centroid(df)

I am running into issues with the 'geosphere' package throwing up an error:

Error in .pointsToMatrix(x, poly = TRUE) : longitude > 360
In addition: Warning message:
In .pointsToMatrix(x, poly = TRUE) :
  Suspect column names (longitude and latitude reversed?)

From reading this stackoverflow post, the issue may be to do with my values formatted in strings rather than numeric/double.

I then proceeded to convert these column values to numeric:

df$lon <- as.numeric(df$lon)
df$lat <- as.numeric(df$lat)

The conversion has seemed to have mucked up my data however as when looking at it now; it shows this:

  index   lat   lon  
 ------- ----- ----- 
      1     1    35  
      2     2     8  
      3     2     9  
      4     2    11  
      5     2    15  
      6     3     9  
      7     3    12  
      8     4    16  
      9     5    13  
     10     5    14  

Does anyone know how I should go about tackling this issue?

Falco
  • 61
  • 7
  • 1
    I am guessing the variables are stored as factors. You can test this. If this is so, you can try `as.numeric(as.character(df$lon))`. – djhurio Jul 20 '18 at 10:23
  • they are, return values like "-0.116 -0.115 -0.115 ...." which seems like they are rounding... – Falco Jul 20 '18 at 10:30

2 Answers2

1

Resolved the issue with a bit of djhurio's help:

Had to convert value first to:

as.character()

The following code now works for my application:

df$lon <- as.numeric(as.character(df$lon))
df$lat <- as.numeric(as.character(df$lat))

center_point <- centroid(df)
Falco
  • 61
  • 7
1
require(sp)
require(rgeos)

x =  'lat,lon
     51.513393,-0.115650 
     51.513428,-0.115461 
     51.513428,-0.115462 
     51.513428,-0.115465 
     51.513428,-0.115470 
     51.513432,-0.115462 
     51.513432,-0.115467  
     51.513435,-0.115471  
     51.513439,-0.115468  
     51.513439,-0.115469'

x = read.table(text = x, sep = ',', header = TRUE, colClasses= rep('numeric', 2) )

sx = SpatialPoints(coords = x[, c('lon','lat')], proj4string = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs") )

gCentroid(sx)


SpatialPoints:
           x        y
1 -0.1154845 51.51343
Coordinate Reference System (CRS) arguments: +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0 
MihaiV
  • 148
  • 8