Create Spatial Data in R

r, spatial

Solution

Here's a start.

## set up a vector of all 10x10 position tags
tags10 <- c(LETTERS,
            paste0("A",LETTERS),
            paste0("B",LETTERS),
            paste0("C",LETTERS[1:22]))

A function to convert (e.g.) `{"J",3}` to the center of the corresponding sub-square.

convpos <- function(pos10,pos5) {
    ## convert letters to major (x,y) positions
    p1 <- as.numeric(factor(pos10,levels=tags10))  ## or use match()
    p1.x <- ((p1-1) %% 10) *10+5    ## %% is modulo operator
    p1.y <- ((p1-1) %/% 10)*10+5    ## %/% is integer division
    ## sort out sub-positions
    p2.x <- ifelse(pos5 <=2,2.5,7.5)   ## {1,2} vs {3,4} values
    p2.y <- ifelse(pos5 %%2 ==1 ,2.5,7.5)  ## odd {1,3} vs even {2,4} values
    c(p1.x+p2.x,p1.y+p2.y)
}

usage:

convpos("J",2)
convpos(mydata$tenbytenpos,mydata$fivebyfivepos)

Important notes:

- this is a proof of concept, I can pretty much guarantee I haven't got the correspondence of x and y coordinates quite right. But you should be able to trace through this line-by-line and see what it's doing ...

- it should work correctly on vectors (see second usage example above): I switched from `switch` to `ifelse` for that reason

- your column names (`10x10`) are likely to get mangled into something like `X10.10` when reading data into R: see `?data.frame` and `?check.names`

Problem

I have a dataset of species and their rough locations in a 100 x 200 meter area. The location part of the data frame is not in a format that I find to be usable. In this 100 x 200 meter rectangle, there are two hundred 10 x 10 meter squares named A through CV. Within each 10 x 10 square there are four 5 x 5 meter squares named 1, 2, 3, and 4, respectively (1 is south of 2 and west of 3. 4 is east of 2 and north of 3). I want to let R know that A is the square with corners at (0 ,0), (10,0), (0,0), and (0,10), that B is just north of A and has corners (0,10), (0,20), (10,10), and (10,20), and K is just east of A and has corners at (10,0), (10,10), (20,0), and (20,10), and so on for all the 10 x 10 meter squares. Additionally, I want to let R know where each 5 x 5 meter square is in the 100 x 200 meter plot. So, my data frame looks something like this ``` 10x10 5x5 Tree Diameter A 1 tree1 4 B 1 tree2 4 C 4 tree3 6 D 3 tree4 2 E 3 tree5 3 F 2 tree6 7 G 1 tree7 12 H 2 tree8 1 I 2 tree9 2 J 3 tree10 8 K 4 tree11 3 L 1 tree12 7 M 2 tree13 5 ``` Eventually, I want to be able to plot the 100 x 200 meter area and have each 10 x 10 meter square show up with the number of trees, or number of species, or total biomass What is the best way to turn the data I have into spatial data that R can use for graphing and perhaps analysis?

Original source