27titanik 27titanik - 5 days ago 5
R Question

How to match the data from a shp file with those contained in a dataframe?

I am drawing spatial samples from a shp file. In this way:

pr <- readShapePoly("PuertoRico.shp")
n <- 90
samp.reg <- spsample(pr, n, type="regular")


This is what I get:

samp.reg
SpatialPoints:
x1 x2
#[1,] -66.15482 17.93279
#[2,] -67.15842 18.02403
#[3,] -67.06718 18.02403
#[4,] -66.97595 18.02403
#[5,] -66.88471 18.02403


And so on, till [90,]

Now, I would like to extract those observations included in the sample just drawn , from the dataframe containing not only the coordinates, but also the connected variable that I need to study (i.e. elevation). Below you can see how the dataframe looks like.

df <- read.csv("pr_elev_rs.csv",header=TRUE)
head(df)
Label x y elevation
1 BL192 -67.27045 18.36269 0
2 BM191 -67.26450 18.36761 30
3 BM192 -67.26490 18.36020 56
4 BM193 -67.26287 18.35222 0
5 BM194 -67.26075 18.34632 0
6 BN190 -67.25191 18.37403 10


I am a beginner with R and I don't know how I can do this. Thank you for the help, I really need it.

Answer

Not sure I have undestood correctly your question.

 match <- df$x %in% samp.reg@coords[,1] & df$y %in% samp.reg@coords[,2]
 extract_df_row <- df[match,]

Is this what you need??

EDIT: now you can subset

 if(nrow(extract_df_row)>0) {
  coordinates(extract_df_row) <- cbind(extract_df_row$x, extract_df_row$y)
  }else{
    cat("no coordinates matching df")
  }
Comments