作者:黄天元,复旦大学博士在读,热爱数据科学与开源工具(R),致力于利用数据科学迅速积累行业经验优势和科学知识发现,涉猎内容包括但不限于信息计量、机器学习、数据可视化、应用统计建模、知识图谱等,著有《R语言高效数据处理指南》(《R语言数据高效处理指南》(黄天元)【摘要 书评 试读】- 京东图书)。知乎专栏:R语言数据挖掘。邮箱:[email protected].欢迎合作交流。
最近在学习R语言空间分析,Geocomputation with R是一本非常优秀的教材,英语简单易懂,代码和例子也非常典型。这里给出https://geocompr.robinlovelace.net/geometric-operations.html#exercises-3我自己做的答案,供参考。如有误,望指正。代码如下:
library(pacman)
# p_install_gh("r-spatial/RQGIS")
p_load(sf,raster,dplyr,spData,spDataLarge,RQGIS)
data(random_points)
data(ndvi)
ch = st_combine(random_points) %>%
st_convex_hull()
# 1
p_load(rmapshaper)
nz["Name"] %>%
st_simplify(dTolerance = .5) %>%
plot()
nz["Name"] %>%
ms_simplify(keep = .5) %>%
plot()
#2
canterbury_not = nz %>% filter(Name != "Canterbury")
canterbury_not_height = nz_height[canterbury_not, ]
canterbury_not_height
st_buffer(canterbury, dist = 1e5) %>%
st_intersection(canterbury_not_height) %>%
nrow # 25
# 3
nz_centroid = nz %>% st_combine() %>% st_centroid()
nz %>% filter(Name == "Canterbury") %>%
st_centroid() -> canterbury_centroid
st_distance(nz_centroid,canterbury_centroid)
# 4
new_geom = st_geometry(world) * c(1,-1)
reverse_world = st_set_geometry(world,new_geom)
plot(world["name_long"])
plot(reverse_world["name_long"])
# 5
b = st_sfc(st_point(c(0, 1)), st_point(c(1, 1))) # create 2 points
b = st_buffer(b, dist = 1) # convert points to circles
plot(b)
text(x = c(-0.5, 1.5), y = 1, labels = c("x", "y")) # add text
x = b[1]
y = b[2]
x_and_y = st_intersection(x, y)
plot(b)
plot(x_and_y, col = "lightgrey", add = TRUE) # color intersecting area
plot(b)
plot(x & y, col = "lightgrey", add = TRUE)
# 6
us_states %>%
mutate(boundary_length = st_length(.)) %>%
arrange(desc(boundary_length)) %>%
slice(1,nrow(.))
# 7
ndvi %>% crop(random_points) -> rp_crop
rp_crop %>% mask(random_points) -> rp_mask
plot(ndvi)
plot(rp_crop)
plot(rp_mask)
# 8
extract(ndvi,random_points) -> rp_ndvi
random_points %>%
st_buffer(dist = 90) -> rp_buffer
extract(ndvi,rp_buffer) %>%
sapply(mean) -> rp_buffer_ndvi
plot(rp_ndvi,rp_buffer_ndvi)
abline(a=0, b=1)
# 9
nz_height %>%
filter(elevation > 3100) -> elev_gt_3100
raster_template = raster(extent(elev_gt_3100), resolution = 3000,
crs = st_crs(elev_gt_3100)$proj4string)
nz_count = rasterize(elev_gt_3100, raster_template,
field = 1, fun = "count")
plot(nz_count)
nz_max_elev = rasterize(elev_gt_3100, raster_template,
field = "elevation", fun = max)
plot(nz_max_elev)
# 10
nz_count %>%
aggregate(fact = 2,fun = sum) -> nz_count_6km
nz_count_6km %>%
disaggregate(fact = 2) -> nz_count_3km
identical(nz_count,nz_count_3km)
# pros:fast,less memory;cons:information loss
# 11
grain
rasterToPolygons(grain) %>%
st_as_sf() %>%
filter(layer == 1) -> grain_clay
grain_clay
# pros:object-oriented analysis;cross platform analysis
# cons:info loss and misuse
# usage: recognize objects from raster data and compare with sf objects