将x和y网格坐标转换为x和y起始结束单元格坐标

时间:2018-12-07 08:12:29

标签: r grid coordinates

我有xy网格坐标(网格单元的起始坐标):

x.coords <- c(-12,-2.2,7.8,17.8,28.8)
y.coords <- c(-37.5,-27.5,-17.5)

我想创建一个data.frame,为该网格中的每个单元格指定其xstartystartxendyend坐标。

因此,在本示例中,生成的data.frame将是:

data.frame(xstart = c(-12,-12,-2.2,-2.2,7.8,7.8,17.8,17.8),
           ystart = c(-37.5,-27.5,-37.5,-27.5,-37.5,-27.5,-37.5,-27.5),
           xend = c(-2.2,-2.2,7.8,7.8,17.8,17.8,28.8,28.8),
           yend = c(-27.5,-17.5,-27.5,-17.5,-27.5,-17.5,-27.5,-17.5))

2 个答案:

答案 0 :(得分:1)

无需循环/应用

x.coords <- c(-12,-2.2,7.8,17.8,28.8)
y.coords <- c(-37.5,-27.5,-17.5)

x.start = x.coords[1:length(x.coords)-1]
y.start = y.coords[1:length(y.coords)-1]
x.end   = x.coords[2:length(x.coords)]
y.end   = y.coords[2:length(y.coords)]

data.frame(
  xstart = rep( x.start, each = length( y.start ) ),
  xend   = rep( x.end, each = length( y.end ) ),
  ystart = rep( y.start, times = length( x.start ) ),
  yend   = rep( y.end, times = length( x.start ) )
)

#   xstart xend ystart  yend
# 1  -12.0 -2.2  -37.5 -27.5
# 2  -12.0 -2.2  -27.5 -17.5
# 3   -2.2  7.8  -37.5 -27.5
# 4   -2.2  7.8  -27.5 -17.5
# 5    7.8 17.8  -37.5 -27.5
# 6    7.8 17.8  -27.5 -17.5
# 7   17.8 28.8  -37.5 -27.5
# 8   17.8 28.8  -27.5 -17.5

答案 1 :(得分:0)

似乎是:

data.frame(xstart = unlist(lapply(head(x.coords,-1),function(x) rep(x,length(y.coords)-1))),
           ystart = rep(head(y.coords,-1),length(x.coords)-1),
           xend = unlist(lapply(x.coords[-1],function(x) rep(x,length(y.coords)-1))),
           yend = rep(y.coords[-1],length(x.coords)-1))