0

Trying to convert a data frame to an sf object via this post (How to Convert data frame to spatial coordinates). However I keep getting the following error.. Error in `[.default`(x, coords) : only 0's may be mixed with negative subscripts

I tried to resolve it based off of this post (R debugging: "only 0's may be mixed with negative subscripts"), thinking because my coordinates were global, R didn't like the range of values. However I subset it to just a the north western hemisphere and recieved the same error. Below is the code I'm using

dat.sf <- st_as_sf(x=dat2,
                   coords = c(dat2$centroid_lon, dat2$centroid_lat),
                   crs= "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")

where dat2 is just the coordinates and a unique ID (group ID) for storm event associated with that lat and long.

UPDATE: I tried a few other things, such as:

coordinates <- as.data.frame(cbind(dat2$centroid_lon, dat2$centroid_lat))
dat.sf <- st_as_sf(x=dat2,
                   coords = coordinates,
                   crs= "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")

and received this Error in `[.default`(x, coords) : invalid subscript type 'list'

and this....

coordinates <- cbind(dat2$centroid_lon, dat2$centroid_lat)
dat.sf <- st_as_sf(x=dat2,
                   coords = coordinates,
                   crs= "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")

and received this Error in as.matrix(x)[i] : subscript out of bounds. traceback() tells me it is definitely an issue with my coordinates.

DPek
  • 160
  • 12

1 Answers1

1

If you look in the docs for st_as_sf you will see that the coords parameter should be:

coords : in case of point data: names or numbers of the numeric columns holding coordinates

So you need to pass the name of the columns but you are passing the columns themselves . You will also see this is how coords is used in the answers you have linked. Therefore if you do:

dat.sf <- st_as_sf(x=dat2,
                   coords = c("centroid_lon", "centroid_lat"),
                   crs= "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")

You should get the correct result.

Allan Cameron
  • 56,042
  • 3
  • 16
  • 39