Skip to content

Instantly share code, notes, and snippets.

@corocorohashiokama
Created April 5, 2025 02:26
Show Gist options
  • Save corocorohashiokama/b29413edacc56be5cc86d183daf28b8c to your computer and use it in GitHub Desktop.
Save corocorohashiokama/b29413edacc56be5cc86d183daf28b8c to your computer and use it in GitHub Desktop.
riv_data_edit
options(encoding = "UTF-8")
library(sf)
library(dplyr)
library(st)
library(units)
riv_hokkaido <- read_sf("")
riv_hokkaido <- st_set_crs(riv_hokkaido, 4612)
riv_hokkaido[["length"]] <- st_length(riv_hokkaido)
#一級河川のみで限定し、長さを調べる。
riv_hokkaido_node <- read_sf("")
#最上流点をリストにする
upstream_point <- which(riv_hokkaido$W05_007 == riv_hokkaido$W05_009)
m <- set_units(numeric(length(upstream_point)), "m")
for (i in upstream_point){
start_num <- riv_hokkaido$W05_010[i]
m[i] <- riv_hokkaido$length[i]
while(TRUE){
next_row <- which(riv_hokkaido$W05_009 == start_num)
if(length(next_row) > 0 ){
m[i] = m[i] + riv_hokkaido$length[i]
post_row <- riv_hokkaido$W05_010[next_row]
start_num <- post_row
}
else{
break
}
}
}
riv_hokkaido["sum_length"] <- m
riv_hokkaido[["sum_length"]] <- drop_units(riv_hokkaido[["sum_length"]])
riv_hokkaido_upstream <- riv_hokkaido[riv_hokkaido$sum_length > 0,]
riv_hokkaido_upstream <-select(riv_hokkaido_upstream, 1:3,5:7,13)
riv_hokkaido_upstream <- st_drop_geometry(riv_hokkaido_upstream)
names(riv_hokkaido_upstream)[6] <- "W05_000"
riv_hokkaido_upstream <- left_join(riv_hokkaido_upstream, riv_hokkaido_node, by = "W05_000")
riv_hokkaido_upstream <- riv_hokkaido_upstream %>%
mutate(
x = sapply(geometry, function(coord) coord[1]),
y = sapply(geometry, function(coord) coord[2])
)
riv_hokkaido_upstream <- riv_hokkaido_upstream %>%
filter(!is.na(x) & !is.na(y))
# sf オブジェクトに変換
riv_hokkaido_upstream <- st_as_sf(riv_hokkaido_upstream, coords = c("x", "y"), crs = 4612)
###########################################################
coast_line <- read_sf("")
coast_line <- st_set_crs(coast_line, 4612)
distance <- st_distance(riv_hokkaido_upstream, coast_line)
min_distance <- apply(distance, 1, min)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment