I have created a data.frame in R . I want to get SpatialLinesDataFrame as a result so I understand that I have to convert the data.frame into lines, the lines into SpatialLines and the SpatialLines into SpatialLinesDataFrame. I did this

filedata.frame=data.frame(matrix(file),ncol=14, byrow=T))

I get the data.frame I want but not the lines. I am sure is basic but why I can't get the lines?

  • How does your dataframe look like? How are the coordinates stored? Did you check ?Lines? Lines need two parameters as input Lines(slinelist, ID) – Iris Sep 17 '15 at 11:30
  • So every line has beginning point and final point. You are right about the Lines, I did it :for (i in seq_along(lines)) { lines[[i]] <- Lines(list(Line(rbind(c(file$x_f[i],file$y_f[i]), c(filedf$x_tr[i], filedf$y_tr[i]) ))), as.character(i)) } – g.f.l Sep 17 '15 at 11:36

Here's an extended example from the sp vignette that demonstrates how to create a 'SpatialLinesDataFrame' from an ordinary 'data.frame' object. I use some sample data created from the lengths of the single 'SpatialLines' via gLength from rgeos. Note that the rownames of the created dataset passed on to SpatialLinesDataFrame must be identical to the previously defined line IDs (in this particular case "a" and "b").


## from the sp vignette:
l1 <- cbind(c(1, 2, 3), c(3, 2, 2))
l2 <- cbind(c(1, 2, 3), c(1, 1.5, 1))

Sl1 <- Line(l1)
Sl2 <- Line(l2)

S1 <- Lines(list(Sl1), ID = "a")
S2 <- Lines(list(Sl2), ID = "b")

Sl <- SpatialLines(list(S1, S2))

## sample data: line lengths
df <- data.frame(len = sapply(1:length(Sl), function(i) gLength(Sl[i, ])))
rownames(df) <- sapply(1:length(Sl), function(i) Sl@lines[[i]]@ID)

## SpatialLines to SpatialLinesDataFrame
Sldf <- SpatialLinesDataFrame(Sl, data = df)

plot(Sldf, col = c("red", "blue"))
text(labels = paste0("length = ", round(Sldf@data$len, 2)), 
     x = gCentroid(Sldf, byid = TRUE)$x,
     y = gCentroid(Sldf, byid = TRUE)$y)

enter image description here

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.