如何向已有的sf点对象中添加新的点要素?
向已有sf对象添加点的正确方法
你之前的错误在于st_point()仅用于创建单个点的几何对象,仅接受坐标向量作为输入,不能传入name、language这类属性参数,这是报错的核心原因。以下是两种正确的添加方式:
方法1:构造单行sf对象后合并
- 创建多伦多的几何对象并指定CRS(需与原sf对象一致,这里为4326):
toronto_sfg <- st_point(c(-79.450717, 43.691589)) toronto_sfc <- st_sfc(toronto_sfg, crs = 4326)
- 构造包含属性的数据框并转为sf对象:
toronto_df <- data.frame( name = "Toronto", language = "English", weather = "hot" ) toronto_sf <- st_sf(toronto_df, geometry = toronto_sfc)
- 合并到原sf对象:
city_profiles <- rbind(city_profiles, toronto_sf)
方法2:一步扩展原sf对象
直接通过rbind()将包含属性和几何的单行数据合并到原对象,无需单独创建sf:
city_profiles <- rbind(city_profiles, data.frame( name = "Toronto", language = "English", weather = "hot", geometry = st_sfc(st_point(c(-79.450717, 43.691589)), crs = 4326) ))
执行完成后,可通过print(city_profiles)验证新点是否成功添加。
内容的提问来源于stack exchange,提问作者plast1cd0nk3y
相关产品推荐
相关产品推荐

