Assign column from an existing dataframe as an attribute column in spatial points vector

Viewed 51

I'm trying to include a column from a existing dataframe in a spatial points vector as an attribute but i'm getting no success.

My data is something like this:

ID x y dsp section
136 592251.4 7775385 -0.0000000002806002 top
726 592319.1 7775182 -0.0000000002805585 top
130 592170.2 7775385 -0.0018586431397125 center
1074 592278.5 7775060 NA center

And I create the spatial points from this same data, using x and y info:

pontos <- vect(cbind(amostragem$x,amostragem$y))
crs(pontos)  <- "epsg:32723"
pontos <- project(pontos,worldDEM)

It's totally functional but when I assign a column that is not a longitude/latitude (x,y) information (the "Section" column is my interest for classification) the vector loses its spatial points characteristics.

And this lead me to work outside R since I've got no time to lose and this was a small quantity of points: Attributes table from QGIS

I exported the vector as a shapefile and went to QGIS ("attribute table") manually adding the column in shp and filling the points (rows) with the information that I wanted. Works perfectly, so I read the shp edited to R again and apply extract using a raster and the edited points. And now I have the attribute as a column. As this is not the smartest for a big volumn of points I want to make this works in R too. Any thoughts?

Thanks for your help.

1 Answers

You could use the sf package to create a spatial data frame. The call to st_as_sf does this and converts the x and y coordinates to a geometry column which is retained when functions in the dplyr package are called.

library(sf)
library(dplyr)

amostragem <- read.table(text="ID x y dsp section
136 592251.4 7775385 -0.0000000002806002 top
726 592319.1 7775182 -0.0000000002805585 top
130 592170.2 7775385 -0.0018586431397125 center
1074 592278.5 7775060 NA center", header=T)

amostragem_sf <- amostragem %>% st_as_sf(coords = c('x', 'y'), crs=st_crs('epsg:32723'))

names(amostragem_sf)
#[1] "ID"       "dsp"      "section"  "geometry"

class(amostragem_sf)
#[1] "sf"         "data.frame"

# add a new column
amostragem_sf <- amostragem_sf %>% mutate(new_column = paste(ID, section))

# new column added
names(amostragem_sf)
#[1] "ID"         "dsp"        "section"    "geometry"   "new_column"

# it's still a spatial data frame
class(amostragem_sf)
#[1] "sf"         "data.frame"
Related