python中的pd.crosstab在R中有类似的函数吗?

Is there any function in R similar to pd.crosstab in python?

我在 python 中寻找类似于 pd.crosstab 的 R 函数,其中,我想根据第三列的总和值在两列之间创建列联矩阵。

例子-

Column1 | Column2 | Column3
A       | X       | 1
A       | Y       | 2
A       | Z       | 3
B       | X       | 1
B       | Y       | 2
B       | Z       | 3

输出

  | X | Y | Z
A | 1 | 2 | 3
B | 1 | 2 | 3

该函数称为交叉表,即 xtabs:

xtabs(Column3~Column1+Column2, df)
       Column2
Column1 X Y Z
      A 1 2 3
      B 1 2 3

对于使用 Tidyverse 替代方案的可重现示例,这里是一个使用 tidyr::pivot_wider() 扩大 table 的解决方案(我发现这个函数比 stats::reshape() 少了 100 倍的混乱) :

# create example dataset
my_data <- data.frame(col1 = rep(c("A", "B"), each = 3),
                      col2 = rep(LETTERS[24:26], 2),
                      col3 = rep(1:3, 2))
# widen the data
library(tidyr)
pivot_wider(my_data,
            names_from = col2,
            values_from = col3)
#> # A tibble: 2 x 4
#>   col1      X     Y     Z
#>   <chr> <int> <int> <int>
#> 1 A         1     2     3
#> 2 B         1     2     3

reprex package (v2.0.0)

于 2021-05-10 创建