按每个组中的子组汇总(&分组)

summarize(&group by) by subgroup in each group

all,我试着求出喜欢苹果的人群和不喜欢苹果的人群的国籍比例(喜欢苹果==1,苹果==0如果不)。我使用此代码,但百分比不是我想要的:

sample %>%
group_by(Apple,Country) %>%
dplyr::summarise(count=n())%>%
mutate(pct_gender=count/sum(count))

我从这段代码中得到的是国籍+苹果在所有观察中的百分比。 (比如31个观察中,有18人喜欢苹果。18个喜欢苹果的人中,有7人来自法国。所以我想得到7/18=38.8%,但我得到的结果是7/31=22.6% )

这是我使用的数据:

structure(list(id = 1:30, Country = c("USA", "USA", "USA", "USA", 
"USA", "USA", "USA", "USA", "Germany", "Germany", "Germany", 
"Germany", "Germany", "Germany", "UK", "UK", "UK", "UK", "UK", 
"UK", "UK", "UK", "UK", "UK", "France", "France", "France", "France", 
"France", "France"), Apple = c(1L, 1L, 1L, 0L, 0L, 1L, 0L, 1L, 
1L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 
1L, 1L, 1L, 1L, 1L, 1L), Banana = c(1L, 1L, 0L, 1L, 1L, 0L, 0L, 
1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 
1L, 1L, 0L, 0L, 0L, 1L, 1L), Orange = c(0L, 0L, 0L, 0L, 0L, 1L, 
1L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 1L, 
1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L), Jackfruit = c(0L, 0L, 1L, 1L, 
0L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 1L, 
1L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L)), row.names = c(NA, -30L
), class = c("tbl_df", "tbl", "data.frame"))

如果有人能告诉我我做错了什么,我将不胜感激。

要得到喜欢和不喜欢的比例,我们可以先group_byCountryApple,统计每组的行数,spread它宽格式,然后计算比率。

sample %>%
  group_by(Country, Apple) %>%
  summarise(perc = n()) %>%
  mutate(Apple = c("dislike", "like")[Apple + 1])  %>%
  tidyr::spread(Apple, perc, fill = 0) %>%
  ungroup() %>%
  mutate_at(vars(dislike, like), ~./sum(.))

# A tibble: 4 x 3
#  Country dislike  like
#  <chr>     <dbl> <dbl>
#1 France    0     0.353
#2 Germany   0.308 0.118
#3 UK        0.462 0.235
#4 USA       0.231 0.294

在 base R 中,使用 table

更简单
dat <-table(sample$Country, sample$Apple)
t(t(dat)/colSums(dat))


#                  0         1
#  France  0.0000000 0.3529412
#  Germany 0.3076923 0.1176471
#  UK      0.4615385 0.2352941
#  USA     0.2307692 0.2941176

我同意@Ronak Shah 的观点,这在基础上比任何其他包都更容易:

使用 table(如 Ronak 所建议的),但也使用 prop.table:

prop.table(table(df$Country, df$Apple), margin = 2)

产生:

                  0         1
  France  0.0000000 0.3529412
  Germany 0.3076923 0.1176471
  UK      0.4615385 0.2352941
  USA     0.2307692 0.2941176

请注意,您不应该期望法国有 38.8% - 喜欢(因为在您的玩具数据中,在 17 个喜欢苹果的人中,只有 6 个法国人喜欢苹果)。