示例 Dataframe
df <- data.frame(countrycode=c("A","B","C"),
hdi_1999 = c(0.7, 0.8, 0.6),
hdi_2000 = c(0.71, 0.81, 0.61),
hdi_2001 = c(0.72, 0.82, 0.62),
icrg_1999 = c(60, 50, 70),
icrg_2000 = c(61, 51, 71),
icrg_2001 = c(62, 52, 72))
我需要的是4列唯一的国家代码年,其中年是_
1999 2000 2001后的数字。
countrycode year hdi icrg
我的准则是
df_new <- df %>%
pivot_longer(cols = starts_with("hdi"),
names_to = c("hdi", "year"),
names_sep = "_",
values_to = "hdi_value",
names_repair = "unique") %>%
pivot_longer(cols = starts_with("icrg"),
names_to = c("icrg", "year"),
names_sep = "_",
values_to = "icrg_value",
names_repair = "unique")
其结果不是唯一的国家代码-年份对
2条答案
按热度按时间ccgok5k51#
我们可以简单地在
pivot_longer
本身中完成此操作nuypyhwy2#
使用
reshape
。