0

Given the following code:

library(data.table)

x<-runif(10)
y<-runif(10)
dt<-data.table( someAtt=sample(c("a","b","c"),10,replace = T), 
   long=x, lat=y, prevLong=shift(x), prevLat=shift(y) )

The resulting data.table looks as follows:

    a       long        lat   prevLong    prevLat
 1: a 0.07082431 0.78423301         NA         NA
 2: b 0.71443287 0.36526340 0.07082431 0.78423301
 3: c 0.09045303 0.67790574 0.71443287 0.36526340
 4: d 0.11502144 0.28482632 0.09045303 0.67790574
 5: e 0.32395554 0.03948988 0.11502144 0.28482632
 6: f 0.22150591 0.94228135 0.32395554 0.03948988
 7: g 0.83432081 0.12126201 0.22150591 0.94228135
 8: h 0.48438370 0.96476431 0.83432081 0.12126201
 9: i 0.55442422 0.55877777 0.48438370 0.96476431
10: j 0.42999165 0.48831255 0.55442422 0.55877777

The data.table/data.frame consists of some attribute and longitude/latitude information. prevLong and prevLat represent the longitude/latitude of the previous row.

What I want is a sf object consisting of 10 line segmenets, each line segment defined by the longitude/latitude information of the rows.

How can I do that?

1

Here's a simple conversion - you don't need the extra columns, just the lat/long of each vertex in the line:

line <- dt[, 2:3] %>%
  as.matrix() %>%
  st_linestring() %>%
  st_sfc() %>%
  st_sf()

edit: wait, if you wanted each line segment on a separate row of your final sf,

ptmat <- dt[, 2:5] %>%
  as.matrix() %>%
  .[2:nrow(.), ]

linesegs <- split(ptmat, 1:nrow(ptmat)) %>%
  lapply(., function(x) {
    x <- matrix(x, nrow = 2, byrow = T)
    x <- st_linestring(x)}) 

final_sf <- st_sfc(linesegs ) %>% 
  st_sf('ID' = 1:length(.)) 
0

you need to use st_linestring function from sf package:

library(data.table)
library(sf)

x<-runif(10)
y<-runif(10)
dt<-data.table(someAtt=sample(c("a","b","c"),10,replace = T), 
                long=x, lat=y, prevLong=shift(x), prevLat=shift(y) )
###(i couln't get it to run with an empty c(), so the
### first value was made before the loop
temp <- st_linestring(rbind(c(dt$long[1], dt$lat[1]), c(dt$prevLong[1], dt$prevLat[1])))
ls <- c(temp)
for(i in 1:dim(dt)[1]){
  temp2 <- st_linestring(rbind(c(dt$long[i], dt$lat[i]), c(dt$prevLong[i], dt$prevLat[i])))
  ls <- c(ls, temp2)
}     

plot(ls)

because of the data, lines appear connected

  • I feel more context is needed for this to be an answer--there is no explanation as to why the OP's code is wrong and this is correct. This also appears to be a hardcoded answer--dependent upon the data that OP provided and not something usable for the next person who needs to split into x amount of line segments. – MaryBeth Oct 2 '17 at 18:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.