例如:
require(reshape2)
var1 = c(rep('john', 3), rep('aron', 2), 'frank')
var2 = c('john', 'aron', 'frank', 'aron', 'frank', 'frank')
var3 = rnorm(6)
mydat = data.frame(var1, var2, var3)
acast(mydat, var1~var2)
结果:
Using var3 as value column: use value.var to override.
aron frank john
aron 0.32026 0.22858 NA
frank NA 0.57658 NA
john 0.30543 1.16453 -2.0021
这打乱了原始顺序,理想情况下,人们希望在下三角形中很好地看到 3 个 NA。
最佳答案
通常,当出现关于“如何保留...的顺序”的问题时,我尝试将 factor
作为第一个解决方案之一,并指定我的 factor
所需的顺序:
mydat$var1 <- factor(mydat$var1, c("john", "aron", "frank"))
mydat$var2 <- factor(mydat$var2, c("john", "aron", "frank"))
acast(mydat, var1~var2)
# Using var3 as value column: use value.var to override.
# john aron frank
# john 0.464706 1.77877633 0.5925874
# aron NA 0.04940059 -0.3180871
# frank NA NA -1.3888493
关于r - 如何在reshape2中使acast保留变量的顺序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19710986/