在 R 中旋转更宽的数据框?

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

我有以下示例

data.frame
,我想对其进行转换,以便我的
Lat & Long
成为列以及每个
Lat & Long
点的行中的日期和数据

DF <- data.frame(Lat = rep(10:12,3),
                 Long = rep(100:102, 3),
                 Data = runif(9,50,60),
                 Date = rep(c("1995-01-01","1995-01-02","1995-01-03"),3))

下面是我希望

data.frame
看起来如何的示例草图。

r dataframe tidyverse pivot-table lubridate
1个回答
0
投票

我在这里依赖于纬度值和经度值之间存在一对一的关系。如果这不是一个可靠的假设,则需要调整。

library(tidyverse)    
bind_rows(
  DF |> 
    distinct(Lat, Long, Date = "Long") |>
    pivot_wider(names_from = Lat, values_from = Long),
  DF |>
    select(-Long) |>
    pivot_wider(names_from = Lat, values_from = Data)
) 
  

结果

# A tibble: 4 × 4
  Date        `10`  `11`  `12`
  <chr>      <dbl> <dbl> <dbl>
1 Long       100   101   102  
2 1995-01-01  57.7  52.9  59.5
3 1995-01-02  52.5  50.3  59.4
4 1995-01-03  54.4  56.8  55.6

数据

DF <- data.frame(Lat = rep(10:12, 3),
                 Long = rep(100:102, 3),
                 Data = runif(9,50,60),                             # see below #
                 Date = rep(c("1995-01-01","1995-01-02","1995-01-03"), each = 3))
© www.soinside.com 2019 - 2024. All rights reserved.