i am completely new in R.
I am trying to save a spatialdataframe and a normal data frame within the same object. when I am applying the code below, it saves the object as a R workspace, is it normal? i mean I wnated to obtain a .rda data instead. What i specifically want to do is to obtain an R data with those two objects. I want the spatialdataframe to keep its spatial charactheristics. Can someone help me?
##import a text table
mcvfinal<-read.csv("dataCPWithAge.csv",header=TRUE,sep=",",dec=".")
##reading the shapefile
library(rgdal) polypc1 <- readOGR(".", "CP3poly_Matchingshp")
##saving the two frames into the same object
save(mcvfinal,polypc1,file="polypc.Rdata")
Try:
saveRDS(list(mcvfinal,polypc1),file="polypc.rds")
Load:
foo = readRDS("polypc.rds")
# mcvfinal is foo[[1]]
# polypc1 is foo[[2]]
Related
I am new to working with Spatial Data in R, and I'm having trouble accessing the polygons and relating the polygons to the data. Here's the thing:
I have municipalities a SpatialPolygonsDataFrame, and I can access the data section with municipalities#data this of course is a data frame and I can do the usual manipulation with sapply and similar functions. I want, however, to create a new variable in data that depends on the polygons. So for example, I would like to do:
municipalities$pointInPolygon <- sapply(POLYGON, function(x){getPointInPolygon{x})
or something similar. Thing is, I still don't understand how the data and polygon sections of my SPDF are related and how to access the later.
Any answers,tips, or resources to understand SpatialPolygonsDataFrames better is appreciated.
PS: Here is the data I'm using and how I am reading it
municipalities <- rgdal::readOGR("México_Estados/México_Estados.shp")
Why not use sf package for simple features:
municipalities_sf <- sf::read_sf("México_Estados.shp")
class(municipalities_sf)
#
> [1] "sf" "tbl_df" "tbl" "data.frame"
#
Then you can use dplyr, purrr, etc on data frame directly:
municipalities_sf |>
dplyr::mutate(purrr::map(geometry, function(x){myFantasticFunction}))
I have created a "ppp" objects in R spatstat package and inserted them into a hyper frame I would like to run test later but how do I save them such that I can access them from my computer every time I need
2. I have imported a text comma-delimited (txt), land cover file and converted them into "ppp" and "im" objects as required in the spatstat package. after conversion, I created a data frame from these two files
library(maptools)
library(spatstat)
point.pattern <- read.table("occ.txt", header=TRUE)
shape <- readshapespatial("polygon")
use shape file as a window by using the as.own function
ow <- as.owin(shape)
convert the txt file into a ppp object.
pattern.ppp <- as.ppp(point.pattern, ow, fatal=TR)
imported the raster file and convert into im object
raster <- raster("land cover.tif")
raster.im <- as.im(raster)
create a hyper frame hyper
frame <- hyperframe(X=pattern.ppp, Y=list(raster.im)
write and save the hyper frame data now
I completely do not know the function to use in order to save my hyper frame data such that I can access them any time from my computer minus rewriting the codes every time
You can save any R object using saveRDS():
saveRDS(frame, "your_filename.rds")
Later you can read it back in with readRDS():
frame <- readRDS("your_filename.rds")
In R, how can I export a khrud object from function kernelUD in package adehabitat to a raster file (geoTiff)?
I tried following this thread (R: how to create raster layer from an estUDm object) using the code here:
writeRaster(raster(as(udbis1,"SpatialPixelsDataFrame")), "udbis1.tif")
where udbis1 is a khrud object, but I get "Error in as(udbis1, "SpatialPixelsDataFrame") : no method or default for coercing “khrud” to “SpatialPixelsDataFrame."
I think the issue may be that the old thread was before an update to the adehabitat package changed the data format from estUD to khrud. Maybe?
You do not provide a reproducible example. The following works for me:
library(adehabitatHR)
library(raster)
data(puechabonsp)
loc <- puechabonsp$relocs
ud <- kernelUD(loc[, 1])
r <- raster(as(ud[[1]], "SpatialPixelsDataFrame"))
writeRaster(r, filename = file.path(tempdir(), "ud1.tif"))
AdehabitatHR solutions work well for data that are in the required format or when using multiple animals. Though when wanting to create KDE with data organized differently or for only one source, it can be frustrating. For some reason, #johaness' answer doesn't work for my case so here is an alternative solution that avoids the headaches of going into adehabitatHR's innards.
library(adehabitatHR)
library(raster)
# Recreating an example for only one animal
# with a basic xy dataset like one would get from tracking
loc<-puechabonsp$relocs
loc<-as.data.frame(loc)
loc<-loc[loc$Name=="Brock",]
coordinates(loc)<-~X+Y
ud<-kernelUD(loc)
# Extract the UD values and coordinates into a data frame
udval<-data.frame("value" = ud$ud, "lon" = ud#coords[,1], "lat" = ud#coords[,2])
coordinates(udval)<-~lon+lat
# coerce to SpatialPixelsDataFrame
gridded(udval) <- TRUE
# coerce to raster
udr <- raster(udval)
plot(udr)
I have a stake in raster data of Landsat and I want to extract the values of them by employing SpatialPointData in R and then plot the extracted values with the associated variables in SpatialPointData and finally, I want to exported the extracted data along with the variable in the attribute of the spatial point object. I have used extract function to do so but the problem is that after extracting I got several errors every time and sometimes it works but it gives me only a data frame as a matrix which I cant match them with observation point.
My scripts
#raster
lsat <- stack(b1,b2,b3,b4,b5,b6_1,b6_2,b7)
#SpatialPoint
soil_sp=SpatialPoints(cbind(soil.clean2$x,soil.clean2$y))
Extrcat the value from stack layer
soil_sp$ref<- extract(lsat2, soil_sp)
plot the extrced value and observed value in point data for each band
plot( soil_sp$ref ~., data=soil_sp)
Finally, I want to export the extracted value along with variable in point data in a single data frame or SpatialPointsDataFrame.
The solution was to use SpatialPointDataFrame to extract the value of stack raster and then write the result into a CSV file or whatever you would like.
implementation:
Crerate SpatialPointDataFram out of SpatialPointData
soil_spdf=SpatialPointsDataFrame(coords = soil_sp,data = soil.clean2,
proj4string = soil_crs)
Extrcat the values.
soil_spdf$ref <- extract(lsat2 , soil_spdf)
write the data in CSV file in the desired directory on your PC.
write.csv(x =soil_spdf,file ="C:/lsat2.csv")
I want to to convert two .shp files into one database that would allow me to draw the maps together.
Also, is there a way to convert .shp files into .csv files? I want to be able to personalize and add some data which is easier for me under a .csv format. What I have in mind if to add overlay yield data and precipitation data on the maps.
Here are the shapefiles for Morocco, and Western Sahara.
Code to plot the two files:
# This is code for mapping of CGE_Morocco results
# Loading administrative coordinates for Morocco maps
library(sp)
library(maptools)
library(mapdata)
# Loading shape files
Mor <- readShapeSpatial("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/MAR_adm1.shp")
Sah <- readShapeSpatial("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/ESH_adm1.shp")
# Ploting the maps (raw)
png("Morocco.png")
Morocco <- readShapePoly("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/MAR_adm1.shp")
plot(Morocco)
dev.off()
png("WesternSahara.png")
WesternSahara <- readShapePoly("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/ESH_adm1.shp")
plot(WesternSahara)
dev.off()
After looking into suggestions from #AriBFriedman and #PaulHiemstra and subsequently figuring out how to merge .shp files, I have managed to produce the following map using the following code and data (For .shp data, cf. links above)
code:
# Merging Mor and Sah .shp files into one .shp file
MoroccoData <- rbind(Mor#data,Sah#data) # First, 'stack' the attribute list rows using rbind()
MoroccoPolys <- c(Mor#polygons,Sah#polygons) # Next, combine the two polygon lists into a single list using c()
summary(MoroccoData)
summary(MoroccoPolys)
offset <- length(MoroccoPolys) # Next, generate a new polygon ID for the new SpatialPolygonDataFrame object
browser()
for (i in 1: offset)
{
sNew = as.character(i)
MoroccoPolys[[i]]#ID = sNew
}
ID <- c(as.character(1:length(MoroccoPolys))) # Create an identical ID field and append it to the merged Data component
MoroccoDataWithID <- cbind(ID,MoroccoData)
MoroccoPolysSP <- SpatialPolygons(MoroccoPolys,proj4string=CRS(proj4string(Sah))) # Promote the merged list to a SpatialPolygons data object
Morocco <- SpatialPolygonsDataFrame(MoroccoPolysSP,data = MoroccoDataWithID,match.ID = FALSE) # Combine the merged Data and Polygon components into a new SpatialPolygonsDataFrame.
Morocco#data$id <- rownames(Morocco#data)
Morocco.fort <- fortify(Morocco, region='id')
Morocco.fort <- Morocco.fort[order(Morocco.fort$order), ]
MoroccoMap <- ggplot(data=Morocco.fort, aes(long, lat, group=group)) +
geom_polygon(colour='black',fill='white') +
theme_bw()
Results:
New Question:
1- How to eliminate the boundaries data that cuts though the map in half?
2- How to combine different regions within a .shp file?
Thanks you all.
P.S: the community in stackoverflow.com is wonderful and very helpful, and especially toward beginners like :) Just thought of emphasizing it.
Once you have loaded your shapefiles into Spatial{Lines/Polygons}DataFrames (classes from the sp-package), you can use the fortify generic function to transform them to flat data.frame format. The specific functions for the fortify generic are included in the ggplot2 package, so you'll need to load that first. A code example:
library(ggplot2)
polygon_dataframe = fortify(polygon_spdf)
where polygon_spdf is a SpatialPolygonsDataFrame. A similar approach works for SpatialLinesDataFrame's.
The difference between my solution and that of #AriBFriedman is that mine includes the x and y coordinates of the polygons/lines, in addition to the data associated to those polgons/lines. I really like visualising my spatial data with the ggplot2 package.
Once you have your data in a normal data.frame you can simply use write.csv to generate a csv file on disk.
I think you mean you want the associated data.frame from each?
If so, it can be accessed with the # slot access function. The slot is called data:
write.csv( WesternSahara#data, file="/home/wherever/myWesternSahara.csv")
Then when you read it back in with read.csv, you can try assigning:
myEdits <- read.csv("/home/wherever/myWesternSahara_modified.csv")
WesternSahara#data <- myEdits
You may need to do some massaging of row names and so forth to get it to accept the new data.frame as valid. I'd probably try to merge the existing data.frame with a csv you read in in R, rather than making edits destructively....