我有一个存储点数据的sf对象。但是,我很难理解如何在这个对象中添加点。
我知道如何在单独的对象中创建两点:
# Create sfg objects with coordinates of Los Angeles and Amsterdam
la_sfg <- st_point(c(-118.2615805, 34.1168926))
amsterdam_sfg <- st_point(c(4.8979755, 52.3745403))
我知道如何将这两个物体组合成一个几何集合:
# Create sfc object with multiple sfg objects
points_sfc <- st_sfc(la_sfg, amsterdam_sfg, crs = 4326)
points_sfc
我还知道如何使用dataframe向这些点添加属性:
# Create a data frame of attributes for the two points
data <- data.frame(name = c("Los Angeles", "Amsterdam"),
language = c("English", "Dutch"),
weather = c("sunny", "rainy/cold"))
# Make sf object from separate data frame and sfc objects
city_profiles <- st_sf(data, geometry = points_sfc)
现在,假设我有另一个点坐标与以下信息:
name = Toronto
language = English
Coordinates = c(-79.450717,43.691589)
weather = hot
我很难弄清楚如何创建一个sfg对象,然后将它添加到我先前存在的特性集合中。例如,直觉上我觉得我会做这样的事情:
# Create sfg object
toronto <- st_point(name = "toronto", language = "English",weather = "cold", geometry=c(-79.450717,43.691589))
然后使用rbind将此特性添加到city_profiles中。但是,这不是正确的语法,只返回错误。
发布于 2022-09-26 18:17:56
正如SymbolixAU所说,您必须从所有点开始执行所有sf
步骤,然后对结果进行rbind
。或者先绑定它,然后使用同一个data.frame中的所有点执行所有的data.frame步骤。例如:
library(tidyverse)
library(sf)
library(rnaturalearth)
world <- rnaturalearth::ne_countries(scale = "small",
returnclass = "sf")
la_ams <- data.frame(name = c("Los Angeles", "Amsterdam"),
language = c("English", "Dutch"),
weather = c("sunny", "rainy/cold"),
lon = c(-118.2615805, 4.8979755),
lat = c(34.1168926, 52.3745403))
la_ams <- sf::st_as_sf(la_ams,
coords = c("lon", "lat"),
crs = 4269)
ggplot() +
geom_sf(data = world,
mapping = aes(geometry = geometry),
fill = "white") +
geom_sf(data = la_ams,
aes(geometry = geometry),
size = 3,
color = "red") +
theme_bw()
再加一点:
toronto <- data.frame(name = c("toronto"),
language = c("English"),
weather = c("cold"),
lon = c(-79.450717),
lat = c(43.691589))
toronto <- sf::st_as_sf(toronto,
coords = c("lon", "lat"),
crs = 4269)
cities <- rbind(la_ams, toronto)
ggplot() +
geom_sf(data = world,
mapping = aes(geometry = geometry),
fill = "white") +
geom_sf(data = cities,
aes(geometry = geometry),
size = 3,
color = "red") +
theme_bw()
https://stackoverflow.com/questions/73860655
复制