R: divide latitude and longitude into grid sections

前端 未结 1 1630
长发绾君心
长发绾君心 2021-01-21 12:10

I have latitude and longitude points:

> d1 <- data.frame(lat, lon)
> head(d1)
       lat       lon
1 43.25724 -96.01955
2 43.25724 -95.98172
3 43.25724          


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 12:23

    One way is to use cut on each axis.

    set.seed(2)
    n <- 50
    df <- data.frame(x = runif(n), y = runif(n))
    head(df)
    #           x           y
    # 1 0.1848823 0.007109038
    # 2 0.7023740 0.014693911
    # 3 0.5733263 0.683403423
    # 4 0.1680519 0.929720222
    # 5 0.9438393 0.275401199
    # 6 0.9434750 0.811859695
    

    Now assign the bins, arbitrarily generating a 3x3 grid:

    df <- within(df, {
      grp.x = cut(x, (0:3)/3, labels = FALSE)
      grp.y = cut(y, (0:3)/3, labels = FALSE)
    })
    head(df)
    #           x           y grp.y grp.x
    # 1 0.1848823 0.007109038     1     1
    # 2 0.7023740 0.014693911     1     3
    # 3 0.5733263 0.683403423     3     2
    # 4 0.1680519 0.929720222     3     1
    # 5 0.9438393 0.275401199     1     3
    # 6 0.9434750 0.811859695     3     3
    

    Now these can be used in grouping, coloring, etc. Here's a graph just for demonstration, but indicating that by color (Y-axis) and shape (X-axis), the points can be processed as a group.

    plot(y ~ x, data = df, pch = (15:17)[grp.x], col = grp.y)
    abline(v = (1:2)/3)
    abline(h = (1:2)/3)
    

    0 讨论(0)
提交回复
热议问题