示例数据框

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") 

其中结果不是唯一的国家代码年对

推荐答案

我们只需在pivot_longer中就可以做到这一点

library(tidyr)
pivot_longer(df, cols = -countrycode, 
   names_to = c(".value", "year"), names_pattern = "(.*)_(\\d{4})$")

-输出

# A tibble: 9 × 4
  countrycode year    hdi  icrg
  <chr>       <chr> <dbl> <dbl>
1 A           1999   0.7     60
2 A           2000   0.71    61
3 A           2001   0.72    62
4 B           1999   0.8     50
5 B           2000   0.81    51
6 B           2001   0.82    52
7 C           1999   0.6     70
8 C           2000   0.61    71
9 C           2001   0.62    72

R相关问答推荐

R中的Fasttext langue_identification返回太多参数-如何与文本匹配?

DT::可数据的正规表达OR运算符问题

有没有方法将paste 0功能与列表结合起来?

使用spatVector裁剪网格数据时出现的问题

在ggplot Likert条中添加水平线

使用ggplot 2根据R中的类别排列Likert比例gplot

从嵌套列表中智能提取线性模型系数

根据模式将一列拆分为多列,并在R中进行拆分

ggplot的轴标签保存在officer中时被剪切

如何在一次运行中使用count进行多列计数

在rpart. plot或fancyRpartPlot中使用带有下标的希腊字母作为标签?

合并后返回列表的数据帧列表

如何识别倒排的行并在R中删除它们?

Data.table';S GForce-将多个函数应用于多列(带可选参数)

从多个可选列中选取一个值到一个新列中

如何在PDF格式的kableExtra表格中显示管道字符?

删除在R中的write.table()函数期间创建的附加行

当由base::限定时,`[.factor`引发NextMethod错误

我正在try 创建一个接近cos(X)的值的While循环,以便它在-或+1-E10范围内

具有自定义仓位限制和计数的GGPLATE直方图