Reputation: 61
I have a dataframe a.fil with Name, Lon and Lat. name1 43.37390 132.9703 name2 43.35311 132.7493 I create objects POINT
point1.sfg <- st_point(unname(unlist(a.fil[1, 2:3])))
point2.sfg <- st_point(unname(unlist(a.fil[2, 2:3])))
class(point1.sfg) [1] "XY" "POINT" "sfg"
I need to create list of objects POINT
ll <- list(point1.sfg, point2.sfg)
class(ll[[1]]) [1] "XY" "POINT" "sfg"
However, my dataframe contains 1000 rows If I use for...
i <- 1
for (i in 1:nrow(a.fil)) {
ll[i] <- st_point(unname(unlist(a.fil[i, 2:3])))
}
I get list with nrow() elemets, but...
class(ll[[1]]) [1] "numeric"
How do I create list of objects POINT from this dataframe? non numeric
Help me!
Upvotes: 1
Views: 827
Reputation: 26258
From a data.frame
you can create an sf
object
library(sf)
df <- data.frame(
name = c("a","b","c")
, lon = 1:3
, lat = 3:1
)
sf <- sf::st_as_sf( df, coords = c("lon","lat" ) )
sf
# Simple feature collection with 3 features and 1 field
# geometry type: POINT
# dimension: XY
# bbox: xmin: 1 ymin: 1 xmax: 3 ymax: 3
# CRS: NA
# name geometry
# 1 a POINT (1 3)
# 2 b POINT (2 2)
# 3 c POINT (3 1)
Then the list of POINTs is just the geometry column
sf$geometry
# Geometry set for 3 features
# geometry type: POINT
# dimension: XY
# bbox: xmin: 1 ymin: 1 xmax: 3 ymax: 3
# CRS: NA
# POINT (1 3)
# POINT (2 2)
# POINT (3 1)
str( sf$geometry )
# sfc_POINT of length 3; first list element: 'XY' num [1:2] 1 3
And if you truly want a list of POINT objects you can remove the sfc
class
unclass( sf$geometry )
# [[1]]
# POINT (1 3)
#
# [[2]]
# POINT (2 2)
#
# [[3]]
# POINT (3 1)
Upvotes: 2