如何在 R 的数据框中创建四个具有相同 ID 的点组合?

问题描述 投票:0回答:2

我目前正在尝试从 R 中的数据框制作正方形(多边形),为了做到这一点(根据这个 guide),我需要一个包含 4 组成对点作为经纬度坐标的数据框.

使用这个例子:

sample_df <- data.frame(id = c(1,2),
                        t = c('2020-01-01','2020-01-01'),
                        intensity = c(1.3,0.6),
                        x1 = c(113.75,114.00),
                        x2 = c(114.00,114.25),
                        y1 = c(8.75,8.75),
                        y2 = c(9.00,9.00))
id t 强度 x1 x2 y1 y2
1 2020-01-01 1.3 113.75 114.00 8.75 9.00
2 2020-01-01 0.6 114.00 114.25 8.75 9.00

我想要实现的是创建一个数据框,保留

t
和分配给
intensity
列的
id
列乘以4对
x1 paired to y1
x2 paired to y1
x2 paired to y2
,和
x1 paired to y2
值作为
lon
lat
列。

预期的输出将是一个看起来像这样的数据框:

id t 强度 lat
1 2020-01-01 1.3 113.75 8.75
1 2020-01-01 1.3 114.00 8.75
1 2020-01-01 1.3 114.00 9.00
1 2020-01-01 1.3 113.75 9.00
2 2020-01-01 0.6 114.00 8.75
2 2020-01-01 0.6 114.25 8.75
2 2020-01-01 0.6 114.25 9.00
2 2020-01-01 0.6 114.00 9.00

我目前被卡住了,但我正在玩

mutate()
包的
dplyr
功能,或者
melt()
reshape2

非常感谢您的投入。

r tidyverse reshape2 melt mutate
2个回答
2
投票

我相信这是 2 个重塑/枢轴:

library(tidyr)
library(dplyr)
sample_df %>%
    pivot_longer(c("x1","x2"), names_to=NULL, values_to="lon") %>%
    pivot_longer(c("y1","y2"), names_to=NULL, values_to="lat")

## A tibble: 8 × 5
#     id t          intensity   lon   lat
#  <dbl> <chr>          <dbl> <dbl> <dbl>
#1     1 2020-01-01       1.3  114.  8.75
#2     1 2020-01-01       1.3  114.  9   
#3     1 2020-01-01       1.3  114   8.75
#4     1 2020-01-01       1.3  114   9   
#5     2 2020-01-01       0.6  114   8.75
#6     2 2020-01-01       0.6  114   9   
#7     2 2020-01-01       0.6  114.  8.75
#8     2 2020-01-01       0.6  114.  9   

lon
变量是正确的 - tibbles 的打印方法确实很奇怪,并且显示(
113.75
114.25
)和
114.0
分别为
114.
114


0
投票

我会

unnest
nested
tibble
(这通常是进行组合组合的非凡方法):

library(tidyr)
x1 = c(113.75,114.00)
x2 = c(114.00,114.25)
y1 = c(8.75,8.75)
y2 = c(9.00,9.00)
tibble(
  id = c(1,2),
  t = c('2020-01-01','2020-01-01'),
  intensity = c(1.3,0.6),
  long = list(c(x1, x2)),
  lat = list(c(y1, y2))
) %>% 
  unnest(c(long, lat))
#> # A tibble: 8 × 5
#>      id t          intensity  long   lat
#>   <dbl> <chr>          <dbl> <dbl> <dbl>
#> 1     1 2020-01-01       1.3  114.  8.75
#> 2     1 2020-01-01       1.3  114   8.75
#> 3     1 2020-01-01       1.3  114   9   
#> 4     1 2020-01-01       1.3  114.  9   
#> 5     2 2020-01-01       0.6  114.  8.75
#> 6     2 2020-01-01       0.6  114   8.75
#> 7     2 2020-01-01       0.6  114   9   
#> 8     2 2020-01-01       0.6  114.  9

创建于 2023-05-04 与 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.