reshape
包裹是你的朋友,在这里。在这种情况下,melt()
并且untable()
对于规范化数据很有用。
如果示例摘要 data.frame 位于名为 的变量中df
,则简短答案为:
# replace total n with number of failures
df$fail = df$n - df$success
df$n = NULL
# melt and untable the data.frame
df = melt(df)
df = untable(df, df$value)
# recode the results, e.g., here by creating a new data.frame
df = data.frame(
test = df$test,
group = df$group,
success = as.numeric(df$variable == "success")
)
这是一个非常普遍的问题的一个很好的例子。这个想法是反向计算交叉表基础的数据列表。给定交叉表,反向计算的数据列表对于每个数据都有一行,并且包含每个数据的属性。 这是与此问题相反的帖子。
用“数据极客”的说法,这是一个将表格数据放入第一范式的问题——如果这对任何人都有帮助的话。您可以 google data normalization,这将帮助您设计可以交叉制表和以多种不同方式分析的敏捷 data.frames。
详细地说,为了melt()
在untable()
这里工作,需要稍微调整原始数据以包含fail
(失败次数) 而不是总数据n
,但这很简单:
df$fail <- df$n - df$success
df$n <- NULL
这使:
test group success fail
1 A control 1 1
2 A treat 2 1
3 B control 3 2
4 B treat 1 2
现在我们可以“融化”桌子了。 melt()
可以反向计算用于创建交叉表的原始数据列表。
df <- melt(df)
在这种情况下,我们得到variable
一个包含“成功”或“失败”的新列,以及一个value
包含原始数据success
或列的数据的fail
列。
test group variable value
1 A control success 1
2 A treat success 2
3 B control success 3
4 B treat success 1
5 A control fail 1
6 A treat fail 1
7 B control fail 2
8 B treat fail 2
该untable()
函数根据数字“计数”向量的值重复表的每一行。在这种情况下,df$value
是计数向量,因为它包含成功和失败的次数。
df <- untable(df, df$value)
这将为每个数据产生一个记录,“成功”或“失败”:
test group variable value
1 A control success 1
2 A treat success 2
2.1 A treat success 2
3 B control success 3
3.1 B control success 3
3.2 B control success 3
4 B treat success 1
5 A control fail 1
6 A treat fail 1
7 B control fail 2
7.1 B control fail 2
8 B treat fail 2
8.1 B treat fail 2
这就是解决方案。如果需要,现在可以重新编码数据以将“成功”替换为 1,将“失败”替换为 0(并去掉无关的value
列variable
......)
df <- data.frame(
test = df$test,
group = df$group,
success = as.numeric(df$variable == "success")
)
这将返回请求的解决方案,但行的排序方式不同:
test group success
1 A control 1
2 A treat 1
3 A treat 1
4 B control 1
5 B control 1
6 B control 1
7 B treat 1
8 A control 0
9 A treat 0
10 B control 0
11 B control 0
12 B treat 0
13 B treat 0
显然,如有必要,可以使用 data.frame。 如何在 R 中对 data.frame 进行排序。