如何将具有两列计数矩阵的数据帧转换为R中具有单个二进制矢量的数据帧?例如,我有一个这样的数据框,其中id是主题的ID,s和f是该主题的“成功”和“失败”的数量,x是描述该主题某些特征的第三个变量。
id s f x
1 0 3 A
2 2 1 A
3 1 2 B
我希望将此数据帧转换为:
id n x
1 f A
1 f A
1 f A
2 s A
2 s A
2 f A
3 s B
3 f B
3 f B
其中n列指示每个试验是成功(s)还是失败(f)。
我确定我可以编写一个函数来执行此操作,但是我想知道是否有预制解决方案。
dd <- read.table(text="id s f x
1 0 3 A
2 2 1 A
3 1 2 B",
header=TRUE)
with(dd,data.frame(
id=rep(id,s+f),
n=rep(rep(c("s","f"),nrow(dd)),c(rbind(s,f))),
x=rep(x,s+f)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句