5 Piping and Grouped Operations
This lecture introduces you to piping as a neat way to organize your code and make it more legible. Moreover you will also learn how to quickly calculate and estimate statistics by sub-populations, so as to compare them.
(ESS_cntry <- ESS %>% # use ESS, then
group_by(cntry) %>% # group by cntry, then
summarize( # Start summarize function.
# weighted number of cases,
wn = sum(pspwght, na.rm = TRUE),
# weighted cases reporting to belong to a discriminated religious minority,
wn_rd = sum(rel_discr_num * pspwght, na.rm = TRUE),
wperc_rd = (wn_rd / wn) * 100 # weighted %,
)) # End of summarize.
# # A tibble: 29 × 4
# cntry wn wn_rd wperc_rd
# <fct> <dbl> <dbl> <dbl>
# 1 Austria 423. 62.2 14.7
# 2 Belgium 356. 43.7 12.3
# 3 Bulgaria 13.6 0 0
# 4 Switzerland 501. 5.85 1.17
# 5 Cyprus 72.7 0.270 0.371
# 6 Czechia 55.4 0.893 1.61
# 7 Germany 416. 32.0 7.69
# 8 Denmark 95.8 10.5 11.0
# 9 Estonia 336. 2.07 0.615
# 10 Spain 199. 8.30 4.17
# # … with 19 more rows
This code shows how you can use %>%
, group_by()
and summarize()
to quickly estimate the share of persons of immigrant origin who feel that they belong to a discriminated religious minority in the country in which they live.
Lecture slides: Piping and Grouped Operations
Today’s exercise: Web Excercise 5