使用 R 的 Table 函数对按另一个变量分组的数据进行交叉制表
Use R's Table function to cross-tabulate data grouped by another variable
背景
这是一个数据框 d
:
d <- data.frame(ID = c("a","a","b","b"),
product_code = c("B78","X31","C12","C12"),
multiple_products = c(1,1,0,0),
stringsAsFactors=FALSE)
问题与我想要的
我正在尝试使用基础 R
的 table
函数制作 multiple_products
的交叉制表式频率 table,但我想这样做所以按 ID
而不是按行。这是我要找的东西:
0 1
1 1
换句话说,table 表示“有 1 个 ID
,其中 multiple_products
等于 0,还有 1 个 ID
,其中它等于 1”。
我试过的
这是我到目前为止使用 dplyr
的尝试:
dtable <- d %>%
group_by(ID) %>%
table(d$multiple_products) %>%
ungroup()
此代码 运行 在我的真实数据集上没有错误,但它给我的结果与 table(d$multiple_products)
相同,即:
0 1
2 2
表示“2 行 multiple_products
等于 0,2 行等于 1”。
在我给你的玩具示例中,这段代码甚至没有 运行,给我以下错误:
Error: Can't combine `ID` <character> and `multiple_products` <double>.
有什么想法吗?
我们需要按组检查n_distinct
library(dplyr)
d %>%
group_by(multiple_products) %>%
summarise(n = n_distinct(ID))
-输出
# A tibble: 2 x 2
multiple_products n
<dbl> <int>
1 0 1
2 1 1
背景
这是一个数据框 d
:
d <- data.frame(ID = c("a","a","b","b"),
product_code = c("B78","X31","C12","C12"),
multiple_products = c(1,1,0,0),
stringsAsFactors=FALSE)
问题与我想要的
我正在尝试使用基础 R
的 table
函数制作 multiple_products
的交叉制表式频率 table,但我想这样做所以按 ID
而不是按行。这是我要找的东西:
0 1
1 1
换句话说,table 表示“有 1 个 ID
,其中 multiple_products
等于 0,还有 1 个 ID
,其中它等于 1”。
我试过的
这是我到目前为止使用 dplyr
的尝试:
dtable <- d %>%
group_by(ID) %>%
table(d$multiple_products) %>%
ungroup()
此代码 运行 在我的真实数据集上没有错误,但它给我的结果与 table(d$multiple_products)
相同,即:
0 1
2 2
表示“2 行 multiple_products
等于 0,2 行等于 1”。
在我给你的玩具示例中,这段代码甚至没有 运行,给我以下错误:
Error: Can't combine `ID` <character> and `multiple_products` <double>.
有什么想法吗?
我们需要按组检查n_distinct
library(dplyr)
d %>%
group_by(multiple_products) %>%
summarise(n = n_distinct(ID))
-输出
# A tibble: 2 x 2
multiple_products n
<dbl> <int>
1 0 1
2 1 1