I have a rasterbrick and point shapefile. I have working code for extracting values of pixels from spatial points, but I need to export results to .csv file. I suppose that the key of this problem is to convert SpatialPointsDataFrame to normal one. But I do not know how to complete this task. Here is part of my code:


# setting working directory
vstupni_adresar <- choose.dir(getwd(), "Zadej cestu k pracovnímu adresáři")
prac_adresar <- setwd(vstupni_adresar)

# choose a raster brick
r <- brick(choose.files(caption = "Načti data vstupující do klasifikace"))

# choose directory, where point shapefile is located
vyber_shp <- choose.dir(getwd(), "Vyber adresář, kde se nachází trénovací data")

# extract values from shapefile
sdata <- readOGR(dsn = vyber_shp, layer = "trenink")
sdata@data <- na.omit(data.frame(sdata@data, extract(r, sdata)))

# export to vsv
df <- fortify(sdata)
csv_zapis <- write.csv(df, file="Data_extrakce.csv")

1 Answer 1


First, this line, nesting na.omit sdata@data <- na.omit(data.frame(sdata@data, extract(r, sdata))) is very dangerous and will likely break your spatial object.

The @data slot is the data.frame associated with your spatial object. If it a point feature class and you would like to save it with the associated coordinates you can pull them from the @coordinates slot.

coordinates(meuse) <- ~x+y
( df <- data.frame(x=coordinates(meuse)[,1], y=coordinates(meuse)[,2], meuse@data) )
write.csv(df, "mydata.csv", row.names=FALSE)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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