R Academy · 강의

sf 패키지로 단순 피처 다루기

sf 표준을 사용해 공간 기하를 읽고 쓰며 조작합니다.

레슨 1/413개 단계

sf 패키지로 단순 피처 다루기은(는) CoddyKit의 무료 R Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 R Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

sf 패키지란 무엇인가요

sf(Simple Features) 패키지는 R에서 지리 공간 벡터 데이터를 다루는 기본 도구입니다. 도형(점, 선, 다각형)을 일반 데이터 프레임의 특수 목록 열에 저장하므로 dplyr 및 ggplot2와 완전히 호환됩니다.

library(sf)

# sf data frames look like regular data frames
# but have a special 'geometry' column
cat('sf version:', packageVersion('sf'), '\n')

# Supported geometry types
cat('Geometry types: POINT, LINESTRING, POLYGON,\n')
cat('               MULTIPOINT, MULTILINESTRING, MULTIPOLYGON,\n')
cat('               GEOMETRYCOLLECTION\n')

read_sf: Shapefile 불러오기

read_sf("file.shp")는 OGR이 지원하는 모든 형식(Shapefile, GeoJSON, GeoPackage, KML 등)을 sf 객체로 읽어옵니다. 도형과 함께 CRS 및 속성 테이블도 자동으로 읽습니다.

library(sf)

# Read a GeoJSON file from a URL
url <- 'https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson'

# For demonstration, use the system example data
nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))

cat('Class:', class(nc), '\n')
cat('Dimensions:', nrow(nc), 'rows x', ncol(nc), 'cols\n')
cat('CRS:', st_crs(nc)$epsg, '\n')
cat('Geometry type:', unique(st_geometry_type(nc)), '\n')
cat('Column names:', paste(names(nc)[1:5], collapse = ', '), '...\n')

st_geometry_type 및 구조

st_geometry_type()은 각 피처의 도형 유형을 반환합니다. geometry 열은 sfc 객체로 구성된 리스트 열입니다. 다른 열과 마찬가지로 이 열을 확인하고, 부분 집합을 만들고, 조작할 수 있습니다.

library(sf)
nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))

# Geometry type for each feature
types <- st_geometry_type(nc)
cat('Unique types:', unique(as.character(types)), '\n')

# The geometry column
geom_col <- st_geometry(nc)
cat('Geometry class:', class(geom_col), '\n')
cat('First geometry:\n')
print(geom_col[[1]])  # MULTIPOLYGON coordinates

# Access as a normal column
nc$area_est <- st_area(nc)  # adds an area column
cat('\nArea column class:', class(nc$area_est), '\n')

st_coordinates: XY 추출

st_coordinates()는 모든 도형에서 원시 좌표 행렬을 추출합니다. 포인트의 경우 2개 열로 이루어진 행렬(X, Y)을 반환합니다. 폴리곤의 경우 모든 링 꼭짓점과 함께 파트 및 폴리곤 인덱스 열도 반환합니다.

library(sf)

# Create simple point features
pts <- st_sfc(
  st_point(c(-80.0, 35.0)),
  st_point(c(-79.5, 35.5)),
  st_point(c(-79.0, 34.8))
)
pts_sf <- st_sf(id = 1:3, geometry = pts)

# Extract coordinates
coords <- st_coordinates(pts_sf)
cat('Coordinates:\n')
print(coords)

# For polygons: includes part (L1) and polygon (L2) columns
nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))
ring_coords <- st_coordinates(nc[1, ])
cat('Polygon ring vertices:', nrow(ring_coords), '\n')
cat('Column names:', colnames(ring_coords), '\n')

데이터 프레임에서 sf 만들기

st_as_sf(df, coords = c('lon', 'lat'), crs = 4326)는 좌표 열이 있는 일반 데이터 프레임을 sf 포인트 객체로 변환합니다. coords 인수에는 x(경도) 열과 y(위도) 열의 이름을 지정합니다.

library(sf)

# Typical scenario: CSV with lon/lat columns
cities <- data.frame(
  name = c('New York', 'Los Angeles', 'Chicago', 'Houston'),
  lon  = c(-74.006, -118.244, -87.629, -95.369),
  lat  = c(40.713,   34.052,   41.878,  29.760),
  pop  = c(8336817, 3979576, 2693976, 2304580)
)

# Convert to sf
cities_sf <- st_as_sf(
  cities,
  coords = c('lon', 'lat'),
  crs    = 4326
)

print(cities_sf)
cat('\nCRS:', st_crs(cities_sf)$epsg, '(WGS84)\n')

st_point, st_linestring, st_polygon

생성자 함수를 사용하면 프로그래밍 방식으로 도형을 만들 수 있습니다. st_point(c(x,y))는 포인트를 만들고, st_linestring(matrix)은 좌표 쌍으로 선을 만들며, st_polygon(list(matrix))은 링 좌표로 폴리곤을 만듭니다.

library(sf)

# POINT
p <- st_point(c(-74.006, 40.713))
cat('Point:', class(p), '\n')

# LINESTRING: a route with 4 waypoints
route_coords <- matrix(
  c(-74.0, 40.7,
    -75.0, 41.0,
    -76.0, 41.5,
    -77.0, 42.0),
  ncol = 2, byrow = TRUE
)
line <- st_linestring(route_coords)
cat('Linestring length:', st_length(line), '\n')  # in degrees (no CRS yet)

# POLYGON: a simple bounding box
bbox_ring <- matrix(
  c(0,0, 1,0, 1,1, 0,1, 0,0),
  ncol = 2, byrow = TRUE
)
poly <- st_polygon(list(bbox_ring))
cat('Polygon area:', st_area(poly), '\n')

sf 객체 그리기

sf 객체에 사용하는 plot() 메서드는 각 속성 열에 대한 간단한 지도를 만듭니다. 속성 패널 없이 도형만 그리려면 plot(st_geometry(sf_obj))을 전달합니다.

library(sf)
nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))

# Plot all attributes (creates a panel per column)
# plot(nc)  # too many panels

# Plot a single attribute
plot(nc['BIR74'],
     main   = 'North Carolina: Births 1974',
     border = 'white',
     lwd    = 0.5)

# Plot geometry only
plot(st_geometry(nc),
     col    = 'lightblue',
     border = 'gray40',
     main   = 'NC Counties')

sf 객체 부분 집합 만들기

sf 객체는 데이터 프레임처럼 동작하므로 [, subset() 또는 dplyr::filter()로 행을 필터링할 수 있습니다. 모든 행 부분 집합 작업에서 도형 열도 자동으로 함께 유지됩니다.

library(sf)
library(dplyr)

nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))

# Base R subsetting
western_nc <- nc[nc$CNTY_ID < 1830, ]
cat('Western counties:', nrow(western_nc), '\n')

# dplyr filter works identically
high_birth <- nc |>
  filter(BIR74 > 3000) |>
  select(NAME, BIR74, geometry)

cat('High-birth counties:', nrow(high_birth), '\n')
cat('Names:', paste(high_birth$NAME[1:3], collapse = ', '), '...\n')

sf와 ggplot2 통합

ggplot2는 geom_sf()를 통해 sf 객체를 기본적으로 지원합니다. 이 함수는 좌표계를 자동으로 처리하고 별도의 준비 없이 포인트, 선 또는 폴리곤 등 올바른 도형 유형을 렌더링합니다.

library(sf)
library(ggplot2)

nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))

# Choropleth map with ggplot2
ggplot(nc) +
  geom_sf(aes(fill = BIR74), color = 'white', lwd = 0.2) +
  scale_fill_viridis_c(
    option = 'plasma',
    name   = 'Births (1974)'
  ) +
  labs(
    title    = 'North Carolina Birth Counts, 1974',
    subtitle = 'County-level data'
  ) +
  theme_minimal()

sf를 디스크에 저장하기

write_sf(sf_obj, 'output.gpkg')(또는 st_write())는 도형과 속성을 디스크에 저장합니다. GeoPackage(.gpkg)는 긴 열 이름과 UTF-8을 지원하고 모든 내용을 하나의 파일에 저장하므로 Shapefile보다 선호됩니다.

library(sf)

nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))

# Write to GeoPackage
out_path <- tempfile(fileext = '.gpkg')
write_sf(nc, out_path)

cat('Written to:', out_path, '\n')
cat('File size:', file.info(out_path)$size / 1024, 'KB\n')

# Round-trip: read back
nc_rt <- read_sf(out_path)
cat('Round-trip features:', nrow(nc_rt), '\n')
cat('Round-trip CRS match:', identical(st_crs(nc), st_crs(nc_rt)), '\n')

sf 요약 및 확인

print(), st_bbox(), st_crs(), summary()를 사용하면 sf 객체를 빠르게 확인할 수 있습니다. st_bbox()는 객체의 CRS 단위로 경계 상자를 이름이 지정된 벡터(xmin, ymin, xmax, ymax)로 반환합니다.

library(sf)
nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))

# Bounding box
bbox <- st_bbox(nc)
cat('Bounding box:\n')
cat('  xmin:', bbox['xmin'], ' xmax:', bbox['xmax'], '\n')
cat('  ymin:', bbox['ymin'], ' ymax:', bbox['ymax'], '\n')

# CRS
crs_info <- st_crs(nc)
cat('\nEPSG:', crs_info$epsg, '\n')
cat('Proj4:', crs_info$proj4string, '\n')

# Attribute summary
cat('\nBIR74 range:',
    range(nc$BIR74)[1], 'to',
    range(nc$BIR74)[2], '\n')

빠른 확인

longitude와 latitude 열이 있는 데이터 프레임이 있습니다(WGS84). 이를 sf 포인트 객체로 변환하는 함수 호출은 무엇인가요?

복습: sf 패키지

핵심 내용:

  • read_sf()는 shapefile, GeoJSON, GeoPackage 및 기타 형식을 불러옵니다
  • st_geometry_type()은 피처별로 POINT, LINESTRING, POLYGON 등의 유형을 반환합니다
  • st_coordinates()는 원시 XY 좌표 행렬을 추출합니다
  • st_as_sf(df, coords = c('x','y'), crs = 4326)는 데이터 프레임에서 sf를 만듭니다
  • 프로그래밍 방식의 생성자: st_point(), st_linestring(), st_polygon()
  • 시각화를 위해 ggplot2에서 plot(sf_obj) 또는 geom_sf()를 사용합니다
  • write_sf()는 GeoPackage, Shapefile, GeoJSON 등의 형식으로 저장합니다
library(sf)

# Quick sf workflow
nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))
cat('Features:', nrow(nc), '\n')
cat('CRS EPSG:', st_crs(nc)$epsg, '\n')
cat('Geom type:', unique(as.character(st_geometry_type(nc))), '\n')
cat('Bbox xmin:', st_bbox(nc)['xmin'], '\n')
무료로 시작

AI 튜터와 함께 R을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
43
레슨
159

자주 묻는 질문

“sf 패키지로 단순 피처 다루기” 강의는 무료인가요?

네 — “sf 패키지로 단순 피처 다루기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 R Academy 강의 전체를 잠금 해제할 수 있습니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“sf 패키지로 단순 피처 다루기”에서 뭘 배우나요?

sf 표준을 사용해 공간 기하를 읽고 쓰며 조작합니다. 브라우저에서 직접 실행하는 실습 코드로 R Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

R Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 R Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“sf 패키지로 단순 피처 다루기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 R Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 R Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. sf 패키지로 단순 피처 다루기
  2. 좌표 참조 체계와 투영
  3. 공간 조인과 연산
  4. leaflet으로 인터랙티브 지도 만들기
← R Academy(으)로 돌아가기