I have a data table as follows, which I need to convert into an sf object:
library(data.table)
DT <- data.table(
ID = c("A", "B", "C", "D", "E"),
Value = 11:15
)
The geometry information for each ID is a character vector with differing number of coordinates making up the linestring. ID "B" has 4 coordinates; ID "C" has 5.
geo <- c("c(-112.116492521272, -112.116492811159, -112.116492812107, -112.116491781569, -112.116482854256, -112.116482819195, -112.116476331207, -112.116476325101, -112.11647589954, 33.3777109072744, 33.377733456163, 33.377733512504, 33.377817189599, 33.3785425053239, 33.3785454379367, 33.3790725760563, 33.3790731291841, 33.3791076444333)",
"c(-112.282916223332, -112.282955145531, -112.282977080374, -112.282986066594, 33.499285198973, 33.4994146786288, 33.4995335119373, 33.4998030580162)",
"c(-112.281058674957, -112.281058522318, -112.281057917087, -112.281057356648, -112.281055594103, -112.281047371356, -112.281048086137, -112.28104821173, 33.4937123457776, 33.4937301348982, 33.4938008007847, 33.4938659107566, 33.4940708243904, 33.4950232493953, 33.4951159682343, 33.4951322463168)",
"c(-112.282978024041, -112.282977000088, -112.282975472281, -112.282975387447, -112.282974470679, -112.282974464144, -112.282974284899, -112.28297410899, -112.282974107453, 33.5011764123633, 33.5013710145493, 33.5016617311961, 33.501678000948, 33.5018530730796, 33.5018546369058, 33.5018887965849, 33.5019223852857, 33.5019226044706)",
"c(-112.282986066594, -112.282985540911, -112.282984156895, -112.282983004093, -112.282982201845, 33.4998030580162, 33.4998965204233, 33.5001425170464, 33.5003478058912, 33.5004906801949)"
)
Adding the geometry information to DT:
DT$geometry <- geo
Now, I need to convert DT into an sf object with geometry specified as sfc_LINESTRING. I tried using st_cast to first convert the character-based geometry variable into linestring, but it yielded an error.
DT_sf <- st_cast(DT$geometry, "LINESTRING")
Error in UseMethod("st_cast") :
no applicable method for 'st_cast' applied to an object of class "character"
This conversion needs to be done for nearly 20,000 rows. So, I am looking for a computationally efficient way to achieve the required result.