如何转换具有相同列名的数据框
How to transform a data frame with identical column names
我有一个像这样的 df:
df <- data.frame( name = c("mouse", "rat"), cont = c(27L, 83L), cont = c(43L, 45L), cont = c(18L, 54L),
treat = c(49040L, 53522L), treat = c(48570L, 22235L), treat = c(138888L, 345667L))
name cont cont cont treat treat treat
mouse 27 43 18 49040 48570 138888
rat 83 45 54 53522 22235 345667
我在 df 上通过 meltData <- melt(df)
执行了 melt
函数,但我得到的所有行都相同,我的意思是:
variable value
cont 27
cont 83
cont 27
cont 83
treat 49040
treat 53522
treat 49040
treat 53522
.
.
.
期望的输出应该是:
variable value
cont 27
cont 83
cont 43
cont 45
treat 49040
treat 53522
treat 48570
treat 22235
.
.
.
我尝试了不同的融化方式,但无法弄清楚我错过了什么。任何帮助将不胜感激。
您可以使用 data.table::melt()
代替:
library(data.table)
setDT(df)
melt(df, id.vars = "name")[, variable := sub("\..+", "", variable)
][, !"name"]
variable value
1: cont 27
2: cont 83
3: cont 43
4: cont 45
5: cont 18
6: cont 54
7: treat 49040
8: treat 53522
9: treat 48570
10: treat 22235
11: treat 138888
12: treat 345667
或 stack()
来自基数 R:
dfl <- stack(df[-1])
dfl$ind <- sub("\..+", "", dfl$ind)
dfl
values ind
1 27 cont
2 83 cont
3 43 cont
4 45 cont
5 18 cont
6 54 cont
7 49040 treat
8 53522 treat
9 48570 treat
10 22235 treat
11 138888 treat
12 345667 treat
数据
df <- data.frame(
name = c("mouse", "rat"),
cont = c(27L, 83L),
cont = c(43L, 45L),
cont = c(18L, 54L),
treat = c(49040L, 53522L),
treat = c(48570L, 22235L),
treat = c(138888L, 345667L)
)
我有一个像这样的 df:
df <- data.frame( name = c("mouse", "rat"), cont = c(27L, 83L), cont = c(43L, 45L), cont = c(18L, 54L),
treat = c(49040L, 53522L), treat = c(48570L, 22235L), treat = c(138888L, 345667L))
name cont cont cont treat treat treat
mouse 27 43 18 49040 48570 138888
rat 83 45 54 53522 22235 345667
我在 df 上通过 meltData <- melt(df)
执行了 melt
函数,但我得到的所有行都相同,我的意思是:
variable value
cont 27
cont 83
cont 27
cont 83
treat 49040
treat 53522
treat 49040
treat 53522
.
.
.
期望的输出应该是:
variable value
cont 27
cont 83
cont 43
cont 45
treat 49040
treat 53522
treat 48570
treat 22235
.
.
.
我尝试了不同的融化方式,但无法弄清楚我错过了什么。任何帮助将不胜感激。
您可以使用 data.table::melt()
代替:
library(data.table)
setDT(df)
melt(df, id.vars = "name")[, variable := sub("\..+", "", variable)
][, !"name"]
variable value
1: cont 27
2: cont 83
3: cont 43
4: cont 45
5: cont 18
6: cont 54
7: treat 49040
8: treat 53522
9: treat 48570
10: treat 22235
11: treat 138888
12: treat 345667
或 stack()
来自基数 R:
dfl <- stack(df[-1])
dfl$ind <- sub("\..+", "", dfl$ind)
dfl
values ind
1 27 cont
2 83 cont
3 43 cont
4 45 cont
5 18 cont
6 54 cont
7 49040 treat
8 53522 treat
9 48570 treat
10 22235 treat
11 138888 treat
12 345667 treat
数据
df <- data.frame(
name = c("mouse", "rat"),
cont = c(27L, 83L),
cont = c(43L, 45L),
cont = c(18L, 54L),
treat = c(49040L, 53522L),
treat = c(48570L, 22235L),
treat = c(138888L, 345667L)
)