使用 Pivot long 对多个变量进行长数据透视

use*_*159 2 r reshape melt tidyr

我正在尝试使用 Tidyr 的 Pivot_longer 将宽表数据重塑为长数据。但是,无法实现结果 - 尝试搜索但找不到确切的场景。

例子:

    x<- read.table(header=T, text='
   Dt1 V1_cur V2_cur V1_count V2_count  Other_1 
     A   10    6     50     10      Abc
     A   12    5     70     11      Xyz
     B   20    7     20     8       Axy
     B   22    8     22     9       Ax
   ')

# The result which I am trying to get is, to have one Character column with values Category-> values (V1,V2) and two measure columns Cur, Count.

# Dt1 Other_1 Category Cur Count
# A   Abc     V1       10   50
# A   Xyz     V1       12   70
# A   Abc     V2       6    10
# A   Xyz     V2       5    11
# B   Abc     V1       20   20
# B   Xyz     V1       22   22
# B   Abc     V2       7    8
# B   Xyz     V2       8    9
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用 Reshape/Gather,但是它导致了其他问题。但是,如果有人可以让我知道是否可以使用 tidyr Pivot Longer 方法实现上述结果。谢谢 !

使用的代码:

pivot_longer(x,cols=c("V1_cur","V2_cur","V1_count","V2_count"),names_to=c("Category"),values_to=c("Cur","Count"))
Run Code Online (Sandbox Code Playgroud)

我无法理解如何正确地将它们分开。

Zhi*_*ang 5

如果您更改变量名称可能会更容易:

x <- x %>% 
  rename(cur_V1 = V1_cur, 
         cur_V2 = V2_cur, 
         count_V1 = V1_count,
         count_V2 = V2_count)
Run Code Online (Sandbox Code Playgroud)

然后,你可以这样使用pivot_longer

x %>% 
  pivot_longer(-c(Dt1, Other_1),
               names_to = c(".value", "Category"), 
               names_sep = "_")
Run Code Online (Sandbox Code Playgroud)
# A tibble: 8 x 5
  Dt1   Other_1 Category   cur count
  <fct> <fct>   <chr>    <int> <int>
1 A     Abc     V1          10    50
2 A     Abc     V2           6    10
3 A     Xyz     V1          12    70
4 A     Xyz     V2           5    11
5 B     Axy     V1          20    20
6 B     Axy     V2           7     8
7 B     Ax      V1          22    22
8 B     Ax      V2           8     9
Run Code Online (Sandbox Code Playgroud)