Suppose I have the following SpatialPointsDataFrame
library(sp)
exdf <- data.frame(cbind(1:10, 41:50, 101:110))
names(exdf) <- c("id", "x", "y")
coordinates(exdf) <- c("x", "y")
I can run the following apply
apply(exdf@data, 1, function(x) {
cat(coordinates(exdf[exdf$id == x["id"],]), "\n")
})
However it seems ridiculous to select from the same data frame within the function. I'm already iterating through it.
Note that, in my actual use, I need to send both the data frame row and the coordinates to another function, so applying only on the exdf@coords is not an option.
Question 1: Is there a way to do this without exdf[exdf$id == x["id"],] part?
Question 2: If not, is there a package that I can use instead of sp for such tasks. I need sp for its over function primarily, and checked also spatstat and decided sp is simpler to use. However using a "data frame" that's not actually a data.frame annoys me.
Thank you.
You can easily transform your SpatialPointsDataFrame into a regular data.frame and then proceed from there:
> df <- as.data.frame(exdf)
> df
id x y
1 1 41 101
2 2 42 102
3 3 43 103
4 4 44 104
5 5 45 105
6 6 46 106
7 7 47 107
8 8 48 108
9 9 49 109
10 10 50 110
> paste(df$x, df$y, sep=' ')
[1] "41 101" "42 102" "43 103" "44 104" "45 105" "46 106" "47 107" "48 108" "49 109" "50 110"
Edit: From the comment, the OP would like to achieve the result in simpler ways but without converting the Spatial*DataFrame into a data.frame. The same result as in his example can be achieved with the following code, but it needs to be changed if additional columns would also be printed/concatenated/processed:
cat(paste(exdf@coords[,1], exdf@coords[,2]), sep='\n')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With