更改订单/翻转R

时间:2016-05-10 15:59:50

标签: r

对于示例数据框:

df <- structure(list(region = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L, 2L, 2L), .Label = c("a", "b", "c", "d"), class = "factor"), 
    result = c(0L, 1L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L), weight = c(0.126, 
    0.5, 0.8, 1.5, 5.3, 2.2, 3.2, 1.1, 0.1, 1.3, 2.5)), .Names = c("region", 
"result", "weight"), row.names = c(NA, 11L), class = "data.frame")

我正在制作一个加权的xtab:

df$region <- factor(df$region)
result <- xtabs(weight ~ result + region, data=df)
result

这是:

      region
result     a     b
     0 6.926 6.900
     1 1.300 3.500

如何翻转xtab,使区域和结果变量相反(即区域为行,结果为列)。

我认为这可能会奏效,但不行!

result <- xtabs(region + (weight ~ result), data=df)

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

只需颠倒条目的顺序:

 xtabs(weight ~ region + result, data=df)