熔化具有互斥值的列并添加原始列

Melting columns with mutually exclusive values and adding an origin column

我有一个看起来像这样的数据框 (m):

a <- rep(c("one","two"),6)
b <- c(1,2,3,4,NA,NA,NA,NA,NA,NA,NA,NA)
c <- c(NA,NA,NA,NA,5,6,7,8,NA,NA,NA,NA)
d <- c(NA,NA,NA,NA,NA,NA,NA,NA,9,10,11,12)
(m <- cbind(a,b,c,d))

我想将其缩减为如下所示的数据框 (n):

e <- seq(1:12)
f <- rep(c("b","c","d"), each = 4)
(n <- cbind(a,e,f))

我试过融化,但显然不成功:

melt(data = m, na.rm=TRUE)

Var1 Var2 value
1     1    a   one
2     2    a   two
3     3    a   one
4     4    a   two
5     5    a   one
6     6    a   two
7     7    a   one
8     8    a   two
9     9    a   one
10   10    a   two
11   11    a   one
12   12    a   two
13    1    b     1
14    2    b     2
15    3    b     3
16    4    b     4
29    5    c     5
30    6    c     6
31    7    c     7
32    8    c     8
45    9    d     9
46   10    d    10
47   11    d    11
48   12    d    12

需要做哪些改动,有没有比 melt 更好的功能?

选项pivot_longer

library(dplyr)
library(tidyr)
m %>%
   pivot_longer(cols = b:d, names_to = 'f', values_to ='e', values_drop_na = TRUE)

数据

m <-  data.frame(a, b, c, d)