将坐标点转换为坐标线-并保留变量

3

我有一个大数据集,其中包含91个不同轨迹的x,y坐标,这些轨迹由变量ID区分:

>     head(trjct)
     t        x      y        z     Etot   ID
1 0.00 696621.4 167730 1680.960 1192.526 sim1
2 0.01 696621.4 167730 1680.959 1192.526 sim1
3 0.02 696621.4 167730 1680.958 1192.526 sim1
4 0.04 696621.4 167730 1680.952 1192.526 sim1
5 0.06 696621.4 167730 1680.942 1192.526 sim1
6 0.08 696621.4 167730 1680.929 1192.526 sim1

我已经成功将这些坐标转换为线条:
  coordinates(trjct) <- ~x+y
  trjct_lines_coords <- lapply(split(trjct, trjct$ID), function(x) Lines(list(Line(coordinates(x))), x$ID[1L])) #first column = row number

然而变量Etot中包含的信息未被包括。我该如何创建一个列表,其中每个行对应一个值和相应的Etot 值?

我想要为这些行创建一个数据框,按id分组(每个行一行),并且我也想保留Etot 中包含的信息。

1个回答

2
这里介绍一种使用sf包的方法,该包很擅长处理几何和空间数据。需要注意的是,要使用geom_sf进行绘图,需要开发版本的ggplot2。这种方法非常简单,体现了sf非常强大,因为它可以很好地与其他tidyverse工具配合使用。我们使用st_as_sf将其转换为sf对象(将点坐标放入几何列中),group_by(ID)summarise将点合并成一个MULTIPOINTEtot合并成一个值,然后使用st_castMULTIPOINT几何对象转换为线条。
library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.0, proj.4 4.9.3
tbl <- read_table2(
  "t        z     Etot   ID
0.00 1680.960 1192.526 sim1
0.01 1680.959 1192.526 sim1
0.02 1680.958 1192.526 sim1
0.04 1680.952 1192.526 sim1
0.06 1680.942 1192.526 sim1
0.08 1680.929 1192.526 sim1"
)
#> Warning in rbind(names(probs), probs_f): number of columns of result is not
#> a multiple of vector length (arg 2)
#> Warning: 1 parsing failure.
#> row # A tibble: 1 x 5 col     row col   expected actual        file         expected   <int> <chr> <chr>    <chr>         <chr>        actual 1     6 ID    ""       embedded null literal data file # A tibble: 1 x 5

lines <- tbl %>%
  st_as_sf(coords = c("t", "z")) %>%
  group_by(ID) %>%
  summarise(Etot = mean(Etot)) %>%
  st_cast("LINESTRING")

ggplot(lines) +
  theme_bw() +
  geom_sf()

创建于2018年3月13日,使用 reprex package (v0.2.0)。

我尝试按照这里的说明安装ggplot2的开发版本:https://gist.github.com/kohske/1150934,但仍然出现了“找不到函数"ggplot"”的错误。 - user1607
该代码片段已经有7年历史了,ggplot2已经有了新的版本。运行 install.packages("devtools"),然后运行 devtools::install_github("tidyverse/ggplot2")。当你运行 library(tidyverse) 时,应该显示你正在使用 ggplot2 版本 2.2.1.9000。 - Calum You

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接