首页 > 解决方案 > 数据操纵:收集或传播或两者兼而有之?

问题描述

我正在尝试更改我的数据框,以便我可以用一些不同的图来查看它。本质上我想比较不同的模型。这就是我所拥有的:

variable = c('A','B','C','A','B','C')
optimal = c(10,20,30,40,80,100)
control = c(15,15,15,15,15,15)
method_1 = c(11,22,28,44,85,95)
method_2 = c(9, 19,31,39,79,102)

df = data.frame(variable, optimal, control, method_1, method_2)
df

所以它看起来像这样:

  variable optimal control method_1 method_2
1        A      10      15       11        9
2        B      20      15       22       19
3        C      30      15       28       31
4        A      40      15       44       39
5        B      80      15       85       79
6        C     100      15       95      102

我需要一些看起来像这样的东西:

  variable  A  B   C
1  optimal 10 20  30
2  optimal 40 80 100
3  control 15 15  15
4  control 15 15  15
5 method_1 11 22  28
6 method_1 44 85  95
7 method_2  9 19  31
8 method_2 39 79 102

我试过收集、传播和转置,但没有任何效果。有什么想法吗?感觉这应该很容易解决,但我无法理解它。提前致谢。

标签: rdplyr

解决方案


你必须先走多远,然后走宽,即

library(dplyr)
library(tidyr)

df %>% 
 pivot_longer(-1) %>% 
 pivot_wider(names_from = variable, values_from = value) %>% 
 unnest()

name         A     B     C
  <chr>    <dbl> <dbl> <dbl>
1 optimal     10    20    30
2 optimal     40    80   100
3 control     15    15    15
4 control     15    15    15
5 method_1    11    22    28
6 method_1    44    85    95
7 method_2     9    19    31
8 method_2    39    79   102

推荐阅读