使用ivot_longer进行重塑时选择组和值集

时间:2019-08-14 00:41:06

标签: r pivot tidyverse tidyr

如中所述 Reshaping multiple sets of measurement columns (wide format) into single columns (long format)
Elegant solution for casting (spreading) multiple columns of character vectors
您可以在tidyr的 pivot_wider()中使用names_to参数的".value"组件来一次增加多个列:

tibble(
  name = LETTERS[1:10],
  a_x = 1:10,
  a_y = -1:-10,
  b_x = 1:10,
  b_y = -1:-10,
  c_x = 1:10,
  c_y = -1:-10,
  d_x = 1:10,
  d_y = -1:-10
) %>% 
 pivot_longer(
  cols = -name,
  names_to = c(".value", "group"),
  names_sep = "_",

)

产生以下结果:

# A tibble: 20 x 6
   name  group     a     b     c     d
   <chr> <chr> <int> <int> <int> <int>
 1 A     x         1     1     1     1
 2 A     y        -1    -1    -1    -1
 3 B     x         2     2     2     2
 4 B     y        -2    -2    -2    -2
 5 C     x         3     3     3     3
 6 C     y        -3    -3    -3    -3
 7 D     x         4     4     4     4
 8 D     y        -4    -4    -4    -4
 9 E     x         5     5     5     5
10 E     y        -5    -5    -5    -5
11 F     x         6     6     6     6
12 F     y        -6    -6    -6    -6
13 G     x         7     7     7     7
14 G     y        -7    -7    -7    -7
15 H     x         8     8     8     8
16 H     y        -8    -8    -8    -8
17 I     x         9     9     9     9
18 I     y        -9    -9    -9    -9
19 J     x        10    10    10    10
20 J     y       -10   -10   -10   -10

这很有用,但是假定后缀提供了要进行枢转的分组组件。但是,有时可能希望绕过前缀,例如, abcd 将出现在组列中,而 xy 将成为两个列。

这显然是在有关此功能here的原始讨论中讨论的,但是如果有解决方案可以实现,我似乎没有任何进展。

我可以使用其他方法,例如使用base reshape()和 varying ,或通过创建枢轴化规范来完成此操作,但是可以使用此工具轻松地完成此操作吗?

1 个答案:

答案 0 :(得分:0)

".value"向量中names_to的位置确定将哪个组件用作新的列名。要将 xy 用作新列,可以使用names_to = c("group", ".value")

library(tidyverse)

tibble(
  name = LETTERS[1:10],
  a_x = 1:10,
  a_y = -1:-10,
  b_x = 1:10,
  b_y = -1:-10,
  c_x = 1:10,
  c_y = -1:-10,
  d_x = 1:10,
  d_y = -1:-10
) %>% 
 pivot_longer(
  cols = -name,
  names_to = c("group", ".value"),
  names_sep = "_",
)
#> # A tibble: 40 x 4
#>    name  group     x     y
#>    <chr> <chr> <int> <int>
#>  1 A     a         1    -1
#>  2 A     b         1    -1
#>  3 A     c         1    -1
#>  4 A     d         1    -1
#>  5 B     a         2    -2
#>  6 B     b         2    -2
#>  7 B     c         2    -2
#>  8 B     d         2    -2
#>  9 C     a         3    -3
#> 10 C     b         3    -3
#> # ... with 30 more rows

reprex package(v0.3.0.9000)于2019-08-14创建