4

Probably a very basic question but I found nothing in the documentation of Simple Features R package.

I'm looking for the native sf function to extract on the fly all the columns of an sf object without the geometries. Just like SP@data with sp objects.

The following function does the job but I would prefer to use a native function :

st_data <- function(SF) { SF[, colnames(SF) != attr(SF, "sf_column"), drop = TRUE]}

A typical use is when I want to merge two sf dataset by attribute (merge does not work with two sf objects) : merge(SF1, st_data(SF2)).

In that case it would be impractical to use st_geometry(SF2) <- NULL because it does not work "on the fly" and I don't want to permanently drop the geometry column and SF2[,1:5,drop=T] is impractical too because I have to look into the object to see where the geometry column is.

Using : sf_0.5-4 - R 3.4.1

4

1 回答 1

6

我们可以使用该st_geometry<-函数并将几何设置为NULL

library(sf)

nc <- st_read(system.file("shape/nc.shp", package="sf"))

nc_df <- `st_geometry<-`(nc, NULL)

class(nc_df)
[1] "data.frame"

如您所见,nc_df现在是一个数据框,所以我认为您可以为您的示例执行以下操作。

merge(SF1, `st_geometry<-`(SF2, NULL))

更新

正如 Gilles 所指出的,另一个函数 ,st_set_geometry也可以完成相同的任务。这可能是一个更好的选择,因为 usingst_set_geometry不需要使用 "``" 和 "<-" 来包围st_geometry函数。

于 2017-09-06T23:02:32.423 回答