《R数据科学》第十一章练习题

美国民主党、共和党和中间派的人数比例是如何随时间而变化的?  

> gss_cat %>% mutate(partyid=fct_collapse(partyid,        #利用fct_collapse函数对因子水平进行同党派类别合并。
    other=c('NO answer',"Don't know", "Other party"),
    rep = c("Strong republican", "Not str republican"),
    ind = c("Ind,near rep", "Independent", "Ind,near dem"),
    dem = c("Not str democrat", "Strong democrat"))) %>%
  filter(partyid %in% c("dem", "rep", "ind")) %>% group_by(year) %>% 
  summarise(democrat=sum(partyid== "dem"),republican=sum(partyid== 'rep'),independent=sum(partyid== 'ind'))   
%>% mutate(total = democrat + republican + independent,
    democrat_ratio = democrat / total,
    republican_ratio = republican / total,
    independent_ratio = independent / total) -> party_ratio
#使用filter()函数筛选出民主党、共和党和中间派的数据,并使用group_by()函数按照年份进行分组。
#然后,使用summarize()函数计算每个年份中各个政党的人数,并计算比例。
> party_ratio
# A tibble: 8 × 8
   year democrat republican independent total democrat_ratio republican_ratio independent_ratio
  <int>    <int>      <int>       <int> <int>          <dbl>            <dbl>             <dbl>
1  2000      921        684        1152  2757          0.334            0.248             0.418
2  2002      923        764         994  2681          0.344            0.285             0.371
3  2004      959        821         991  2771          0.346            0.296             0.358
4  2006     1436       1132        1851  4419          0.325            0.256             0.419
5  2008      721        505         746  1972          0.366            0.256             0.378
6  2010      696        461         822  1979          0.352            0.233             0.415
7  2012      699        442         765  1906          0.367            0.232             0.401
8  2014      825        537        1088  2450          0.337            0.219             0.444
>ggplot(party_ratio,aes(x=year))+
  geom_line(aes(y=democrat_ratio,color='dem'))+
  geom_line(aes(y=republican_ratio,color='rep'))+
  geom_line(aes(y=independent_ratio,color='ind')) +
  scale_y_continuous(limits = c(0, 1))+
  labs(x = "Year", y = "Ratio", color = "Party") +
  theme_minimal()
#可以使用ggplot2包来绘制折线图,横轴为年份,纵轴为比例。使用geom_line()函数绘制折线图,
#并使用scale_y_continuous()函数设置纵轴的刻度范围。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值