简体   繁体   中英

R - SpatialPointsDataFrame from a list of SpatialPoints

How to create a SpatialPointsDataFrame from a list of SpatialPoints?

In the following there´sa code of a list containing SpatialPoints:.

SP1 <- SpatialPoints(cbind(1,5))
SP2 <- SpatialPoints(cbind(2,4))
SP3 <- SpatialPoints(cbind(3,3))

SP.l<-list(SP1,SP2, SP3)

What I´m looking for is a way to extract the SpatialPoints from the list and create a SpatialPointsDataFrame out of it.

With the following code I can get single SpatialPoints out of the list:

coords_3 = SP.l[[3]]@coords
data_3 = as.data.frame(SP.l[[3]])

SPDF_3 <- SpatialPointsDataFrame(coords=coords_3, data=as.data.frame(data_3))

However I´d like receive all at once. Maybe something like:

SP <- SpatialPoints(lapply(1:length(lidR.clip.SP.l), function(i) {

...

EDIT: what was missing was:

SP.l <- do.call("rbind", SP.l)

That´s what I was actually looking for.

thx!

Since there is no minimal working example as hrbrmstr. You need to provide one. For now, I use a sample data from the GISTools package and demonstrate one way. There is a data set call newhaven in the package. breach is the data. I made a copy of it and created foo , which class is SpatialPoints . I created two list elements using foo .

Using your code, I looped through each list element and converted SpatialPoints to SpatialPointsDataFrame. I hope you can figure out how to apply the following code to your case.

library(GISTools)

data(newhaven)  
foo <- breach

mylist <- list(foo1 = breach[1:10, ],
               foo2 = breach[11:20, ])

lapply(1:length(mylist), function(x){
    SpatialPointsDataFrame(coords = mylist[[x]]@coords,
                           data = as.data.frame(mylist[[x]]))
})

If you want to bind all SPDFs, then you can try the following.

do.call(rbind, lapply(1:length(mylist), function(x){
                   SpatialPointsDataFrame(coords = mylist[[x]]@coords,
                                          data = as.data.frame(mylist[[x]]))
          })
)

what was missing was:

SP.l <- do.call("rbind", SP.l)

That´s what I was actually looking for.

thx!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM