R语言中为sf数据框添加列并保留结构的方法及构建sf数据框
给sf对象添加列并保留结构的方法
sf对象本质是带几何列的数据框,常规的数据框列操作都能直接用,且不会破坏其sf结构,以下是几种常用方法:
1. 直接用$赋值添加列
比如给departements_L93添加一列随机生成的绘图数据:
# 添加随机数值列 departements_L93$plot_data <- runif(nrow(departements_L93), min = 0, max = 100)
执行后departements_L93依然是sf对象,可直接用plot()或配合ggplot2::geom_sf()、tmap等工具绘图。
2. 用dplyr的mutate()添加列
如果习惯tidyverse语法,mutate()完全兼容sf对象:
library(dplyr) departements_L93 <- departements_L93 %>% mutate(plot_data = runif(n(), 0, 100), # n()获取当前行数 category = ifelse(plot_data > 50, "高", "低")) # 可同时添加多列
执行后直接返回sf对象,无需额外转换。
3. 用cbind()合并列
如果已有行数匹配的单独数据框,可直接合并:
# 创建与sf对象行数一致的数据框 extra_df <- data.frame(plot_data = runif(nrow(departements_L93), 0, 100)) # 合并后仍为sf对象 departements_L93 <- cbind(departements_L93, extra_df)
从头生成sf数据框的方法
如果因特殊情况(比如几何列与数据框完全分离)需要从头构建sf对象,有两种常用方式:
1. 用st_sf()组合数据框和几何列
若已有普通数据框和单独的sf几何对象,可通过st_sf()合并:
# 提取原sf对象的几何列 geom_col <- st_geometry(departements_L93) # 生成不带几何列的普通数据框并添加新列 data_df <- departements_L93 %>% st_drop_geometry() data_df$new_plot_data <- runif(nrow(data_df), 0, 100) # 重新生成sf对象,指定坐标系 new_sf_obj <- st_sf(data_df, geometry = geom_col, crs = st_crs(departements_L93))
2. 用st_as_sf()将坐标数据转为sf对象
如果只有经纬度或投影坐标数据,可指定坐标列和坐标系生成sf对象:
# 示例:含投影坐标的数据框 point_data <- data.frame( name = c("A", "B", "C"), x = c(600000, 650000, 700000), # 2154坐标系下的X坐标 y = c(6500000, 6450000, 6400000) # 2154坐标系下的Y坐标 ) # 转为点类型sf对象 point_sf <- st_as_sf(point_data, coords = c("x", "y"), crs = 2154)
内容的提问来源于stack exchange,提问作者iturrizaga
相关产品推荐
相关产品推荐

