head(data) id C1 C2 C3 B1 B2 B3 Name 12 3 12 8 1 3 12 Agar 14 4 11 9 5 -6ren">
gpt4 book ai didi

r - 如何从 reshape2 包中获取 "back"熔化功能?

转载 作者:行者123 更新时间:2023-12-04 10:57:44 25 4
gpt4 key购买 nike

这是我的数据:

> head(data)

id C1 C2 C3 B1 B2 B3 Name
12 3 12 8 1 3 12 Agar
14 4 11 9 5 12 14 LB
18 7 17 6 7 14 16 YEF
20 9 15 4 3 11 17 KAN

所以我使用了 reshape2 包中的 melt 函数来重组我的数据。现在看起来像这样:

dt <- melt(data, measure.vars=2:7)

> head(dt)

n v variable value rt
1 id Name p C1 1
2 12 Agar p 3 2
3 14 LB p 4 3
4 18 YEF p 7 6
5 20 KAN p 9 3
6 id Name u C2 1

我对我的数据进行了一些计算,现在多了一列。我们称它为“rt”。我现在想用这个额外的列将我的数据转换为以前的“状态”。你知道有什么有用的功能吗?

dput(dt)
structure(list(n = structure(c(5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L,
3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L,
4L, 5L, 1L, 2L, 3L, 4L), class = "factor", .Label = c("12", "14",
"18", "20", "id")), v = structure(c(4L, 1L, 3L, 5L, 2L, 4L, 1L,
3L, 5L, 2L, 4L, 1L, 3L, 5L, 2L, 4L, 1L, 3L, 5L, 2L, 4L, 1L, 3L,
5L, 2L, 4L, 1L, 3L, 5L, 2L), class = "factor", .Label = c("Agar",
"KAN", "LB", "Name", "YEF")), variable = structure(c(1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L,
4L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L), .Label = c("p",
"u", "k", "l", "t", "h"), class = "factor"), value = c("C1",
"3", "4", "7", "9", "C2", "12", "11", "17", "15", "C3", "8",
"9", "6", "4", "B1", "1", "5", "7", "3", "B2", "3", "12", "14",
"11", "B3", "12", "14", "16", "17")), .Names = c("n", "v", "variable",
"value"), row.names = c(NA, -30L), class = "data.frame")

最佳答案

在“reshape2”宇宙中,melt*cast 齐头并进。

下面是一个熔化data.frame 并将其dcast恢复为原始形式的示例。您需要对数据采取类似的方法。

mydf <- data.frame(A = LETTERS[1:3], B = 1:3, C = 4:6)
mydf
# A B C
# 1 A 1 4
# 2 B 2 5
# 3 C 3 6

library(reshape2)

mDF <- melt(mydf, id.vars="A")
mDF
dcast(mDF, A ~ variable, value.var="value")
# A B C
# 1 A 1 4
# 2 B 2 5
# 3 C 3 6

dcast 步骤中,将 ~ 之前的项目视为“id”变量,将其后的项目视为结果列名。 value.var 应该是值将从中填充到由 id 变量和列名创建的结果“网格”中的列。

关于r - 如何从 reshape2 包中获取 "back"熔化功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19633713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com