【发布时间】:2019-11-26 22:51:55
【问题描述】:
所有,我试图获得喜欢苹果的人群和不喜欢苹果的人群中的国籍百分比(如果这个人喜欢,Apple==1,如果不喜欢,Apple==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"))
如果有人能告诉我我做错了什么,将不胜感激。
【问题讨论】: