问题描述
I have this dataframe (with dummy values)
Country lifeExp_1952 lifeExp_1962 pop_1952 pop_1962 gdp_1952 gdp_1962
A 1 4 7 10 13 16
B 2 5 8 11 14 17
C 3 6 9 12 15 18
我想将其转换为长格式,但对 lifeExp、pop 和 gdp 有单独的列,如下所示:
Country Year lifeExp pop gdp
A 1952 1 7 13
A 1962 4 10 16
B 1952 2 8 14
B 1962 5 11 17
C 1952 3 9 15
C 1962 6 12 18
到目前为止,我已经能够使用 reshape2 在同一列中提取带有 lifeExp、pop 和 gdp 的年份,但我不知道如何给它们自己的列。
解决方法
我们可以使用pivot_longer
library(dplyr)
library(tidyr)
df1 %>%
pivot_longer(cols = -Country,names_to = c(".value",'Year'),names_sep = "_")
-输出
# A tibble: 6 x 5
# Country Year lifeExp pop gdp
# <chr> <chr> <int> <int> <int>
#1 A 1952 1 7 13
#2 A 1962 4 10 16
#3 B 1952 2 8 14
#4 B 1962 5 11 17
#5 C 1952 3 9 15
#6 C 1962 6 12 18
数据
df1 <- structure(list(Country = c("A","B","C"),lifeExp_1952 = 1:3,lifeExp_1962 = 4:6,pop_1952 = 7:9,pop_1962 = 10:12,gdp_1952 = 13:15,gdp_1962 = 16:18),class = "data.frame",row.names = c(NA,-3L))