且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

合并不同维度的列表元素

更新时间:2023-12-05 16:36:52

我们可以将gather数据转换为长格式,但不包括yearArea列,unite year然后是spread宽格式.

We can gather data to long form excluding year and Area column, unite the year and then spread it to wide format.

library(dplyr)
library(tidyr)

df %>%
  gather(key, value, -year, -Area) %>%
  unite(key, key, year, sep = "") %>%
  spread(key, value)

#  Area N2017 N2018 P2017 P2018
#1    1     5     1     5     1
#2    2     6     2     6     2
#3    3     7     3     7     3
#4    4    NA     4    NA     4