[英]How to output pd.crosstab function in python using survey weight?
[英]Is there any function in R similar to pd.crosstab in python?
我正在寻找 R 中的 function 类似于 python 中的 pd.crosstab ,其中,我想根据值在 2 列之间创建列联矩阵的总和。
例子 -
Column1 | Column2 | Column3
A | X | 1
A | Y | 2
A | Z | 3
B | X | 1
B | Y | 2
B | Z | 3
Output
| X | Y | Z
A | 1 | 2 | 3
B | 1 | 2 | 3
function 称为交叉表,即xtabs
:
xtabs(Column3~Column1+Column2, df)
Column2
Column1 X Y Z
A 1 2 3
B 1 2 3
对于使用 Tidyverse 替代方案的可重现示例,这是一个使用tidyr::pivot_wider()
来扩大表格的解决方案(我发现 function 比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
由代表 package (v2.0.0) 于 2021 年 5 月 10 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.