3

例如:

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。

4

1 回答 1

3

通常,当出现关于“我如何保留...的顺序”的问题时,我会尝试factor作为第一个解决方案之一并指定我factor的 s 所需的顺序:

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
于 2013-10-31T15:49:30.820 回答