[R-sig-Geo] df with embedded wkt lists to sf
Howard, Tim G (DEC)
t|m@how@rd @end|ng |rom dec@ny@gov
Thu Jun 9 21:48:06 CEST 2022
Howdy all -
There's probably a way to do this much more simply than I've figured it out, so it's a bit embarrassing but here goes. I'm getting data out of a shiny app that looks like the following, with lists of coordinates within separate longitude and latitude columns.
Is there more efficient way to get an `sf` collection than what I've got? Perhaps an `apply` replacement for the for() loop? Using a tibble because that's how `googlesheets4` gives it to me.
# set up a couple of lines strings. lists within data.frame/tibble
txtString <- 'structure(list(comment = c("line one", "line two"),
longitude = list("-115.138577; -114.942454; -114.170219", "-118.411382; -118.153971; -117.83527; -117.246901; -117.026262; -117.185613"),
latitude = list("37.527588; 38.234088; 38.368805", "41.296472; 41.645606; 41.819467; 41.837741; 41.590604; 41.333312")),
row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"))'
dat <- dget(textConnection(txtString))
# function for parsing the text strings
getWKT <- function(x){
st_linestring(matrix(
c(as.numeric(unlist(strsplit(x$longitude[[1]],";"))),
as.numeric(unlist(strsplit(x$latitude[[1]],";")))),
byrow = FALSE, ncol = 2)
)
}
# populate dataframe/tibble by going back to sf text
dat$wkt <- NA
for(i in 1:nrow(dat)){
dat$wkt[[i]] <- st_as_text(getWKT(dat[i,]))
}
# finally make the sf collection
dat_sf <- st_as_sf(dat, wkt = "wkt", crs = 4326)
Thanks in advance for any tips.
Tim
More information about the R-sig-Geo
mailing list