例如:
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个NAs。
答案 0 :(得分:3)
通常,当有关“如何保留...的顺序”的问题出现时,我会尝试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