Working with Weights and Sampling Designs for Official Statistics

Tidy Survey Analysis in R
uRos 2026 Tutorial - Paris

Introduction

Instructors

Stephanie
Zimmer

RTI

Rebecca
Powell

Fors Marsh

Isabella
Velásquez

Posit

Overview of tutorial

At the end of this tutorial, you should be able to:

  • Specify a survey design in R to create a survey object
  • Calculate point estimates and their standard errors with survey data
  • Create tables and graphs incorporating survey data and standard errors

Logistics

Libraries needed for today

Note: These are already installed in Posit Cloud

library(tidyverse)
library(survey)
library(srvyr)
library(gt)
library(sf)
library(tmap)

R packages for survey analysis

  • {survey} package first on CRAN in 2003
    • descriptive analysis
    • statistical testing
    • modeling
    • weighting
  • {srvyr} package first on CRAN in 2016
    • “wrapper” for {survey} with {tidyverse}-style syntax
    • only descriptive analysis

Why use {srvyr} over {survey}?

  • Use the pipe function %>% or |>
  • Ability to use tidy selection
  • Functions follow snake_case convention

Comparison of {dplyr} and {srvyr} functions

Apply {dplyr} functions to survey objects

  • A few functions in {srvyr} have counterparts in {dplyr}
    • dplyr::summarize() and srvyr::summarize()
    • dplyr::group_by() and srvyr::group_by()
  • Based on the object class, R will recognize which package to use

Using summarize() to calculate mean and median

towny |> 
  summarize(
    area_mean = mean(land_area_km2, na.rm=TRUE)
  )
# A tibble: 1 × 1
  area_mean
      <dbl>
1      373.
api_des |> 
  summarize(
    score_mean = survey_mean(api99, na.rm=TRUE)
  )
# A tibble: 1 × 2
  score_mean score_mean_se
       <dbl>         <dbl>
1       629.          10.1

Grouping

towny |> 
  group_by(csd_type) |> 
  summarize(area_mean = mean(land_area_km2))
# A tibble: 5 × 2
  csd_type     area_mean
  <chr>            <dbl>
1 city             498. 
2 municipality     607. 
3 town             183. 
4 township         363. 
5 village           23.0
api_des |>
  group_by(stype) |>
  summarize(score_mean = survey_mean(api99, na.rm=TRUE))
# A tibble: 3 × 3
  stype score_mean score_mean_se
  <fct>      <dbl>         <dbl>
1 E           636.          13.3
2 H           617.          15.8
3 M           610.          16.8

Using {srvyr} functions on non-survey objects

towny |>
  summarize(area_mean = survey_mean(land_area_km2))
Error in `summarize()`:
ℹ In argument: `area_mean = survey_mean(land_area_km2)`.
Caused by error in `cur_svy()`:
! Survey context not set

European Social Survey (ESS)

Overview

  • Conducted across Europe every 2 years since 2002
  • Cross-sectional sample (new samples each round)
  • Topics include living conditions, social structure, public opinion and attitudes
  • Sampling designs vary by country but have oversight for rigor
  • This tutorial uses round 11 (fieldwork 2023–2024)

Countries for round 11

Map of Europe with the 30 countries in ESS round 11 shaded in color and labeled with their two-letter codes; non-participating countries are grey. Participating countries: Austria, Belgium, Bulgaria, Croatia, Cyprus, Estonia, Finland, France, Germany, Greece, Hungary, Iceland, Ireland, Israel, Italy, Latvia, Lithuania, Montenegro, Netherlands, Norway, Poland, Portugal, Serbia, Slovakia, Slovenia, Spain, Sweden, Switzerland, Ukraine, and the United Kingdom.

Read data subset for this course

  • This dataset is a subset of columns from the full ESS file
  • Includes derived variables we created for this course
  • See data cleaning code
ess_der <- read_rds(here::here("DerivedData", "ess11_der.rds"))

Why weight? Why use the design?

  • Differential selection probabilities and nonresponse are accounted for in analytic weights
  • Weights are post-stratified by gender, age, education, and geographic region (more in the design section)
  • Not using weights can lead to bias
  • Ignoring strata and clusters usually makes standard errors too small and uses the wrong degrees of freedom, so CIs are too narrow and tests too liberal

Estimates changing with weights

Small-multiple chart with one panel per ESS round 11 country, showing the estimated percentage of people whose main activity in the last 7 days was retirement, with 95% confidence intervals, under four analysis approaches: weights, strata, and clusters; weights only; strata and clusters only; and no design. The two weighted approaches give the same estimate, as do the two unweighted approaches, but weighted and unweighted estimates often differ. Unweighted estimates are higher in most countries, by up to about 14 percentage points (Slovakia 22% weighted vs. 37% unweighted; Ireland 16% vs. 29%; Iceland 7% vs. 21%), and lower in a few (Poland 36% vs. 31%). Confidence interval widths are similar across approaches, mostly 2 to 7 percentage points.

ESS Variable Viewer

Sampling designs

Sampling methods

Units can be selected in various ways such as:

Simple random sampling

(with or without replacement)

Every unit has the same chance of being selected

Systematic sampling

Sample from an ordered list, selecting individuals at an interval with a random starting point

Probability proportional to size

Probability of selection is proportional to “size”

Complex designs

Designs can also incorporate stratification and/or clustering:

Stratified sampling

Divide population into mutually exclusive subgroups (strata). Randomly sample within each stratum

Clustered sampling

Divide population into mutually exclusive subgroups (clusters). Randomly sample clusters, then individuals within clusters

Why does design matter?

  • The design type impacts the variability of the estimates

  • Weights impact the point estimate and the variability estimates

  • Specifying the components of the design (strata and/or clusters) and weights in R is necessary to get correct estimates

Determining the design

  • Check the documentation such as methodology, design, analysis guide, or technical documentation

  • Documentation will indicate the variables needed to specify the design. Look for:

    • Weight (almost always)
    • Strata and/or clusters/PSUs (sometimes labeled pseudo-strata/pseudo-clusters) — or, instead, replicate weights
    • Finite population correction or population sizes (uncommon)
  • Documentation may include SAS, SUDAAN, Stata and/or R syntax

Design-based vs. replicate weights

Two ways to tell R about a sampling design, depending on what the documentation provides:

Strata / clusters / weights are available

Use as_survey_design()

Only replicate weights are available

Use as_survey_rep()

  • Some surveys provide both; others release only replicate weights to protect respondent confidentiality
  • Either path produces a tbl_svy object that works the same way downstream

Specifying sampling designs in {srvyr} without replicate weights

Syntax for common designs: no stratification/clustering

Simple Random Sample (SRS)

apisrs %>% as_survey_design(fpc = fpc)

One-stage cluster sample with a FPC variable

apiclus1 %>% as_survey_design(ids = dnum, weights = pw, fpc = fpc)

Two-stage cluster sample, weights computed from population size

apiclus2 %>% as_survey_design(ids = c(dnum, snum), fpc = c(fpc1, fpc2))

Stratified SRS

apistrat %>% as_survey_design(strata = stype, weights = pw)

Stratified, cluster design

apistrat %>% as_survey_design(ids = dnum, strata = stype, weights = pw, nest = TRUE)

What does the design object look like?

data(api, package = "survey")

apistrat_des <- apistrat |>
  select(cds, stype, api00, pw, fpc) |>
  as_survey_design(strata = stype, weights = pw)

apistrat_des
Stratified Independent Sampling design (with replacement)
Called via srvyr
Sampling variables:
  - ids: `1` 
  - strata: stype 
  - weights: pw 
Data variables: 
  - cds (chr), stype (fct), api00 (int), pw (dbl), fpc (dbl)

Specifying sampling designs in {srvyr} with replicate weights

as_survey_rep(): syntax

  • as_survey_rep() creates a tbl_svy object that then correctly calculates weighted estimates and SEs
scd_rep <- scd |>
  as_survey_rep(
    type = "BRR",
    repweights = starts_with("rep"),
    combined_weights = FALSE
  )

scd_rep
Call: Called via srvyr
Balanced Repeated Replicates with 4 replicates.
Sampling variables:
  - repweights: `rep1 + rep2 + rep3 + rep4` 
Data variables: 
  - ESA (int), ambulance (int), arrests (dbl), alive (dbl), rep1
    (dbl), rep2 (dbl), rep3 (dbl), rep4 (dbl)

Recap

  • Design type (SRS, stratified, clustered) shapes the variability of estimates
  • Weights shape both point estimates and variance
  • Two paths to a tbl_svy object:
    • as_survey_design(): strata, clusters/PSUs, weights
    • as_survey_rep(): replicate weights (BRR, Fay’s, jackknife, bootstrap)
  • Once built, the design object is ready for weighted summaries in later sections

ESS sampling and weighting

Methodology

Recall, we said: “Check the documentation such as methodology, design, analysis guide, or technical documentation”

Head to the ESS website and click “Methodology”: europeansocialsurvey.org/methodology/sampling

Sampling

Key sampling principles, from the ESS Sampling Guidelines:

  • Samples represent all persons aged 15+ living in private households in each country
  • Individuals are selected by strict random probability methods at every stage — no quota sampling, no substitution of non-responders
  • Each country targets a minimum “effective achieved sample size” (1,500, or 800 in countries with populations under 2 million)
  • Exact designs (single-stage, stratified, multi-stage/clustered) vary by country, but every country’s data include psu (primary sampling unit) and stratum variables

Weighting

Four weighting variables are available: Analysis weight (anweight - combination of pspwght and pweight), Post-stratification weight (pspwght), Design weight (dweight), and Population weight (pweight).

dweight — corrects for unequal selection probabilities within a country

pspwght — further adjusts dweight for nonresponse/noncoverage using age, gender, education, region

pweight — rescales each country to its population size, for combining countries in one analysis

anweight — dweight + pspwght + pweight combined; recommended for all analyses

Weighting: the provided code

Clicking into the “weighting guide,” we find example R code using anweight, the recommended weight:

library(survey) # estimation

# Define sample design
design <- svydesign(ids = ~psu, strata = ~stratum, weights = ~anweight,
data = data1)

First attempt

Using exactly the syntax from the weighting guide, we get an error:

svydesign(
  ids = ~ psu,
  strata = ~ stratum,
  weights = ~ anweight,
  data = ess_der
)
Error in `svydesign.default()`:
! Clusters not nested in strata at top level; you may want nest=TRUE.

Why the error?

A handful of psu codes repeat across different stratum values in the raw file:

ess_der |>
  distinct(cntry, psu, stratum) |>
  add_count(psu) |>
  filter(n > 1)
# A tibble: 6 × 4
  cntry   psu stratum     n
  <chr> <int>   <int> <int>
1 HU    12809     855     2
2 HU    13338     815     2
3 HU    13247     855     2
4 HU    13247     779     2
5 HU    12809     851     2
6 HU    13338     884     2

By default, svydesign() assumes cluster (psu) IDs are unique across the whole data set. nest = TRUE tells it to relabel clusters so they’re uniquely identified within each stratum instead. This is the same nest = TRUE we saw in the stratified, cluster design example earlier.

Applying weights, fixed

Including nest = TRUE, we get the design object:

ess_des_true <- svydesign(
  ids = ~ psu,
  strata = ~ stratum,
  weights = ~ anweight,
  data = ess_der,
  nest = TRUE
)

ess_des_true
Stratified 1 - level Cluster Sampling design (with replacement)
With (24791) clusters.
svydesign(ids = ~psu, strata = ~stratum, weights = ~anweight, 
    data = ess_der, nest = TRUE)

From {survey} to {srvyr}

The same design, specified with tidy syntax:

ess_des <- ess_der |>
  as_survey_design(
    ids = psu,
    strata = stratum,
    weights = anweight,
    nest = TRUE
  )

ess_des

Same result: a tbl_svy object ready for weighted summaries.

From {survey} to {srvyr}

Stratified 1 - level Cluster Sampling design (with replacement)
With (24791) clusters.
Called via srvyr
Sampling variables:
  - ids: psu 
  - strata: stratum 
  - weights: anweight 
Data variables: 
  - cntry (chr), anweight (dbl), nwspol (int), netusoft (int),
    netustm (int), volunfp (int), happy (int), wrhpp (int),
    agegroup (int), pdwrk (int), edctn (int), uempla (int),
    uempli (int), dsbld (int), rtrd (int), cmsrv (int), hswrk
    (int), dngoth (int), dngref (int), dngdk (int), dngna (int),
    stratum (int), psu (int), pdwrk_rec (int), edctn_rec (int),
    uempla_rec (int), uempli_rec (int), dsbld_rec (int),
    rtrd_rec (int), cmsrv_rec (int), hswrk_rec (int), dngoth_rec
    (int), Retired (lgl), wt1 (dbl), Happy_Freq (int), Happy
    (int), News (int), Country (chr), Volunteer_12 (int),
    Volunteer_01 (dbl), Volunteer_Factor (fct), NetUsage (dbl),
    NetFreq (fct), AgeGroup (fct)

Derived variables

Handling missing data codes

  • Often multiple types of missing data in surveys
    • Refused
    • Don’t know
    • Valid skip
  • ESS uses 7s (7,77,7777), 8s, and 9s as missing data codes
  • If we leave them as is, means and statistics will be skewed incorrectly
    • Need to recode missing data values as missing (NA)

Recoding missing data

ess_des_edit <-
  ess_des |>
  mutate(
    Happy = if_else(happy %in% c(77, 88, 99), NA, happy),
    News = if_else(nwspol %in% c(7777, 8888, 9999), NA, nwspol),
    Volunteer_Factor = case_when(
      volunfp == 1 ~ "Yes",
      volunfp == 2 ~ "No",
      TRUE ~ NA
    ) |>
      factor(levels = c("Yes", "No")),
    AgeGroup = recode_values(
      agegroup,
      1 ~ '15-24',
      2 ~ '25-34',
      3 ~ '35-44',
      4 ~ '45-54',
      5 ~ '55-64',
      6 ~ '65-74',
      7 ~ '75+'
    ) |>
      fct_reorder(agegroup)
  )

Viewing recodes on design object

ess_des_edit |> 
  survey_count(happy,Happy)
# A tibble: 14 × 4
   happy Happy        n   n_se
   <int> <int>    <dbl>  <dbl>
 1     0     0   296.    25.1 
 2     1     1   200.    24.4 
 3     2     2   495.    42.0 
 4     3     3   964.    55.6 
 5     4     4  1225.    59.9 
 6     5     5  4094.   123.  
 7     6     6  4390.   123.  
 8     7     7  8953.   193.  
 9     8     8 13208.   287.  
10     9     9  7296.   188.  
11    10    10  5364.   143.  
12    77    NA    78.8   17.7 
13    88    NA   141.    19.6 
14    99    NA     5.68   4.10
ess_des_edit$variables |> 
  count(happy,Happy)
# A tibble: 14 × 3
   happy Happy     n
   <int> <int> <int>
 1     0     0   313
 2     1     1   221
 3     2     2   570
 4     3     3  1139
 5     4     4  1534
 6     5     5  4920
 7     6     6  4631
 8     7     7  9459
 9     8     8 13870
10     9     9  7899
11    10    10  5341
12    77    NA    80
13    88    NA   127
14    99    NA    12

Descriptive analysis

Common workflow

  1. Create a tbl_svy object (a survey object) using as_survey_design() or as_survey_rep()

  2. Subset data (if needed) using filter() (to create subpopulations)

  3. Specify domains of analysis using group_by()

  4. Within summarize(), specify variables to calculate, including means, totals, proportions, quantiles, and more

Descriptive functions

Use within summarize()

  • survey_mean(x)
  • survey_median(x)
  • survey_prop()
  • survey_quantile(x)
  • survey_ratio(num, den)
  • survey_sd(x)
  • survey_total(x)
  • survey_var(x)

Common arguments

  • na.rm = FALSE
  • vartype = c("se", "ci", "var", "cv"): defaults to just “se”
  • level = 0.95: confidence level of CIs
  • deff = FALSE: note can specify as logical OR “replace”
  • df = NULL: degrees of freedom for CIs (defaults to degf(design))

Mean examples

News: minutes per day spent on news about politics and current affairs (nwspol)

ess_des |>
  filter(cntry == "IS") |>
  summarize(
    default = survey_mean(News),
    narm = survey_mean(News, na.rm = TRUE)
  )
# A tibble: 1 × 4
  default default_se  narm narm_se
    <dbl>      <dbl> <dbl>   <dbl>
1      NA        NaN  56.9    3.27
ess_des |>
  filter(cntry == "IS") |>
  summarize(
    all = survey_mean(News, na.rm = TRUE, vartype = c("se", "ci", "var", "cv")),
    none = survey_mean(News, na.rm = TRUE, vartype = NULL)
  )
# A tibble: 1 × 7
    all all_se all_low all_upp all_var all_cv  none
  <dbl>  <dbl>   <dbl>   <dbl>   <dbl>  <dbl> <dbl>
1  56.9   3.27    50.4    63.3    10.7 0.0575  56.9
ess_des |>
  filter(cntry == "IS") |>
  summarize(
    ci95 = survey_mean(News, na.rm = TRUE, vartype = "ci", level = 0.95),
    ci80 = survey_mean(News, na.rm = TRUE, vartype = "ci", level = 0.8),
    ci95_df10 = survey_mean(News, na.rm = TRUE, vartype = "ci", level = 0.95, df = 10)
  )
# A tibble: 1 × 9
   ci95 ci95_low ci95_upp  ci80 ci80_low ci80_upp ci95_df10
  <dbl>    <dbl>    <dbl> <dbl>    <dbl>    <dbl>     <dbl>
1  56.9     50.4     63.3  56.9     52.7     61.1      56.9
# ℹ 2 more variables: ci95_df10_low <dbl>, ci95_df10_upp <dbl>
ess_des |>
  filter(cntry == "IS") |>
  summarize(News_mean = survey_mean(News, na.rm = TRUE, deff = "replace"))
# A tibble: 1 × 3
  News_mean News_mean_se News_mean_deff
      <dbl>        <dbl>          <dbl>
1      56.9         3.27           1.39

Proportions: motivation

And still thinking about different ways of trying to improve things in [country] or help prevent things from going wrong, during the last 12 months, have you done any of the following? Have you volunteered for a not-for-profit or charitable organisation? (volunfp)

  • 1: Yes
  • 2: No
  • 7: Refusal*
  • 8: Don’t know*
  • 9: No answer*

Derived variables: Volunteer_01 (1 = Yes, 0 = No) and Volunteer_Factor (factor with levels Yes, No)

Proportions: two methods

Two methods for proportions

  1. For binary outcomes, use survey_mean(x)
    • x is either 1/0 or TRUE/FALSE
    • can use with across() and several outcomes
  2. Group the data by the variable (x) and then use survey_prop()
    • x can have 2 or more levels
    • analyzes only one outcome at a time

Proportions: two methods, examples

ess_des |>
  filter(cntry == "SE") |>
  mutate(Volunteer_lgl = as.logical(Volunteer_01)) |>
  summarize(
    across(
      c(Volunteer_lgl, Volunteer_01),
      ~ survey_mean(.x, na.rm = TRUE)
    )
  )
# A tibble: 1 × 4
  Volunteer_lgl Volunteer_lgl_se Volunteer_01 Volunteer_01_se
          <dbl>            <dbl>        <dbl>           <dbl>
1         0.260           0.0139        0.260          0.0139
ess_des |>
  filter(cntry == "SE", !is.na(Volunteer_Factor)) |>
  group_by(Volunteer_Factor) |>
  summarize(p = survey_prop())
# A tibble: 2 × 3
  Volunteer_Factor     p   p_se
  <fct>            <dbl>  <dbl>
1 Yes              0.260 0.0139
2 No               0.740 0.0139

Proportions: proportion argument

proportion argument in survey_mean()

ess_des |>
  filter(cntry == "SE", !is.na(Volunteer_01)) |>
  summarize(
    p1 = survey_mean(
      Volunteer_01,
      vartype = "ci",
      proportion = FALSE
    ),
    p2 = survey_mean(
      Volunteer_01,
      vartype = "ci",
      proportion = TRUE
    )
  )

Proportions: proportion argument

# A tibble: 1 × 6
     p1 p1_low p1_upp    p2 p2_low p2_upp
  <dbl>  <dbl>  <dbl> <dbl>  <dbl>  <dbl>
1 0.260  0.232  0.287 0.260  0.233  0.288

Proportions: prop_method argument

prop_method sets the CI method when proportion = TRUE (the default in survey_prop())

ess_des |>
  filter(cntry == "SE", !is.na(Volunteer_Factor)) |>
  group_by(Volunteer_Factor) |>
  summarize(
    p1 = survey_prop(vartype = "ci", prop_method = "logit"),
    p2 = survey_prop(vartype = "ci", prop_method = "mean"),
    p3 = survey_prop(vartype = "ci", prop_method = "xlogit")
  )

Subgroup analysis

  • filter() (as in the examples above) subsets the data after the design object is created, so standard errors stay correct
  • Use group_by() to implement domain analysis

Subgroup analysis: mean and median

  • NetUsage is 0 if a person uses internet never, only occasionally, or a few times a week; otherwise the reported minutes using internet on a typical day
ess_des |>
  group_by(Country) |>
  summarize(
    Pop = survey_total(vartype = NULL) * 10000,
    NetUse_mean = survey_mean(NetUsage, na.rm = TRUE),
    NetUse_median = survey_median(NetUsage, na.rm = TRUE)
  ) |>
  gt() |>
  fmt_number(columns = starts_with("NetUse"), decimals = 2) |>
  fmt_number(columns = Pop, decimals = 0) |>
  opt_interactive()

Subgroup analysis: mean and median

Crosstabs: marginal

  • NetFreq is how often people use the internet (categorical)
  • AgeGroup is a categorical age variable
  • With group_by(AgeGroup, NetFreq), proportions sum to 1 within each age group
ess_des |>
  filter(cntry == "FR", !is.na(NetFreq), !is.na(AgeGroup)) |>
  group_by(AgeGroup, NetFreq) |>
  summarize(
    N = survey_total() * 10000,
    p = survey_prop() * 100
  ) |>
  print(n = Inf)

Crosstabs: marginal

# A tibble: 32 × 6
# Groups:   AgeGroup [7]
   AgeGroup NetFreq                   N    N_se      p  p_se
   <fct>    <fct>                 <dbl>   <dbl>  <dbl> <dbl>
 1 15-24    Only occasionally    40255.  40255.  0.436 0.434
 2 15-24    A few times a week   54941.  54941.  0.595 0.593
 3 15-24    Most days           985974. 246792. 10.7   2.49 
 4 15-24    Every day          8159303. 586824. 88.3   2.71 
 5 25-34    Only occasionally   184533.  92304.  2.71  1.33 
 6 25-34    Most days           264448. 101815.  3.89  1.46 
 7 25-34    Every day          6356212. 475560. 93.4   1.88 
 8 35-44    Never                41591.  41591.  0.486 0.487
 9 35-44    Only occasionally    97612.  56513.  1.14  0.661
10 35-44    A few times a week  151262.  76563.  1.77  0.882
11 35-44    Most days           528423. 152299.  6.18  1.70 
12 35-44    Every day          7738219. 497974. 90.4   2.07 
13 45-54    Never               215268. 106143.  2.39  1.16 
14 45-54    Only occasionally   421050. 133341.  4.67  1.44 
15 45-54    A few times a week  363809. 126531.  4.03  1.37 
16 45-54    Most days           799547. 185506.  8.87  1.98 
17 45-54    Every day          7218228. 480960. 80.0   2.78 
18 55-64    Never               768230. 168859.  8.34  1.74 
19 55-64    Only occasionally   967739. 181369. 10.5   1.90 
20 55-64    A few times a week  663439. 150366.  7.20  1.54 
21 55-64    Most days          1017673. 166705. 11.0   1.76 
22 55-64    Every day          5794517. 409369. 62.9   2.86 
23 65-74    Never              1293236. 229568. 17.5   2.82 
24 65-74    Only occasionally   583407. 147059.  7.88  1.89 
25 65-74    A few times a week  673845. 143267.  9.11  1.77 
26 65-74    Most days           824274. 159904. 11.1   1.98 
27 65-74    Every day          4025921. 329504. 54.4   3.42 
28 75+      Never              2899842. 326820. 48.5   3.93 
29 75+      Only occasionally   658894. 151520. 11.0   2.33 
30 75+      A few times a week  407123. 132835.  6.80  2.07 
31 75+      Most days           492333. 125324.  8.23  2.07 
32 75+      Every day          1525627. 214869. 25.5   3.17 

Crosstabs: joint

  • interact() treats each AgeGroup × NetFreq combination as one group
  • Proportions sum to 1 across all cells, not within each age group
ess_des |>
  filter(cntry == "FR", !is.na(NetFreq), !is.na(AgeGroup)) |>
  group_by(interact(AgeGroup, NetFreq)) |>
  summarize(
    N = survey_total() * 10000,
    p = survey_prop() * 100
  ) |>
  print(n = Inf)

Crosstabs: joint

# A tibble: 32 × 6
   AgeGroup NetFreq                   N    N_se       p   p_se
   <fct>    <fct>                 <dbl>   <dbl>   <dbl>  <dbl>
 1 15-24    Only occasionally    40255.  40255.  0.0716 0.0716
 2 15-24    A few times a week   54941.  54941.  0.0977 0.0975
 3 15-24    Most days           985974. 246792.  1.75   0.432 
 4 15-24    Every day          8159303. 586824. 14.5    0.917 
 5 25-34    Only occasionally   184533.  92304.  0.328  0.164 
 6 25-34    Most days           264448. 101815.  0.470  0.181 
 7 25-34    Every day          6356212. 475560. 11.3    0.762 
 8 35-44    Never                41591.  41591.  0.0740 0.0740
 9 35-44    Only occasionally    97612.  56513.  0.174  0.101 
10 35-44    A few times a week  151262.  76563.  0.269  0.136 
11 35-44    Most days           528423. 152299.  0.940  0.268 
12 35-44    Every day          7738219. 497974. 13.8    0.782 
13 45-54    Never               215268. 106143.  0.383  0.188 
14 45-54    Only occasionally   421050. 133341.  0.749  0.235 
15 45-54    A few times a week  363809. 126531.  0.647  0.223 
16 45-54    Most days           799547. 185506.  1.42   0.325 
17 45-54    Every day          7218228. 480960. 12.8    0.823 
18 55-64    Never               768230. 168859.  1.37   0.296 
19 55-64    Only occasionally   967739. 181369.  1.72   0.315 
20 55-64    A few times a week  663439. 150366.  1.18   0.264 
21 55-64    Most days          1017673. 166705.  1.81   0.294 
22 55-64    Every day          5794517. 409369. 10.3    0.714 
23 65-74    Never              1293236. 229568.  2.30   0.402 
24 65-74    Only occasionally   583407. 147059.  1.04   0.259 
25 65-74    A few times a week  673845. 143267.  1.20   0.252 
26 65-74    Most days           824274. 159904.  1.47   0.278 
27 65-74    Every day          4025921. 329504.  7.16   0.591 
28 75+      Never              2899842. 326820.  5.16   0.558 
29 75+      Only occasionally   658894. 151520.  1.17   0.269 
30 75+      A few times a week  407123. 132835.  0.724  0.236 
31 75+      Most days           492333. 125324.  0.876  0.223 
32 75+      Every day          1525627. 214869.  2.71   0.381 

Hands-on exercise

Our goal

Variable explorer

Set up Posit Cloud

  • Sign in to Posit Cloud and head here: bit.ly/uRos26-survey-exercises
  • Click New Project > New Project from Template
  • Choose uros-2026-weights-survey-rstudio or uros-2026-weights-survey-positron (depending on your IDE preferences) > OK

Exercise 1: make the design object

Follow along: Exercises template | Solutions.

Use ess_der and {srvyr} to create a survey design object called ess_des. The ESS design variables are:

  • psu: primary sampling unit (cluster)
  • stratum: stratum
  • anweight: analysis weight

Remember that some psu codes repeat across different stratum values.

Stratified 1 - level Cluster Sampling design (with replacement)
With (24791) clusters.
Called via srvyr
Sampling variables:
  - ids: psu 
  - strata: stratum 
  - weights: anweight 
Data variables: 
  - cntry (chr), anweight (dbl), nwspol (int), netusoft (int),
    netustm (int), volunfp (int), happy (int), wrhpp (int),
    agegroup (int), pdwrk (int), edctn (int), uempla (int),
    uempli (int), dsbld (int), rtrd (int), cmsrv (int), hswrk
    (int), dngoth (int), dngref (int), dngdk (int), dngna (int),
    stratum (int), psu (int), pdwrk_rec (int), edctn_rec (int),
    uempla_rec (int), uempli_rec (int), dsbld_rec (int),
    rtrd_rec (int), cmsrv_rec (int), hswrk_rec (int), dngoth_rec
    (int), Retired (lgl), wt1 (dbl), Happy_Freq (int), Happy
    (int), News (int), Country (chr), Volunteer_12 (int),
    Volunteer_01 (dbl), Volunteer_Factor (fct), NetUsage (dbl),
    NetFreq (fct), AgeGroup (fct)

Exercise 1: make the design object

ess_des <- ess_der |>
  as_survey_design(
    ids = psu,
    strata = stratum,
    weights = anweight,
    nest = TRUE
  )

ess_des

Exercise 2: estimate weighted mean happiness by country

  • Happy is the ESS happy item (0 = extremely unhappy, 10 = extremely happy)
  • Refusal/don’t know/no answer codes already recoded to NA

Use ess_des from Exercise 1 to estimate weighted mean happiness by country.

# A tibble: 30 × 3
   Country  Happy_mean Happy_mean_se
   <chr>         <dbl>         <dbl>
 1 Austria        7.85        0.0494
 2 Belgium        7.70        0.0464
 3 Bulgaria       6.33        0.0549
 4 Croatia        7.53        0.0569
 5 Cyprus         6.99        0.0888
 6 Estonia        7.31        0.0535
 7 Finland        8.04        0.0427
 8 France         7.43        0.0445
 9 Germany        7.59        0.0675
10 Greece         6.80        0.0369
# ℹ 20 more rows

Exercise 2: estimate weighted mean happiness by country

happy_by_country <-
  ess_des |>
  filter(!is.na(Happy)) |>
  group_by(Country) |>
  summarize(Happy_mean = survey_mean(Happy, na.rm = TRUE))

happy_by_country

Likert chart: weighted response distribution by country

A Likert-style stacked bar shows the full weighted distribution of raw 0–10 responses within each country.

Exercise 3: calculate distribution of happiness level by country

Hint: use interact(cntry, Country) in group_by() so proportions are calculated within each country.

# A tibble: 327 × 5
    cntry Country        Happy_factor                  n        p
    <chr> <chr>          <fct>                     <dbl>    <dbl>
  1 AT    Austria        0 - Extremely unhappy    2.90   0.00374 
  2 AT    Austria        1                        1.99   0.00256 
  3 AT    Austria        2                        3.83   0.00493 
  4 AT    Austria        3                       10.9    0.0141  
  5 AT    Austria        4                        8.62   0.0111  
  6 AT    Austria        5                       43.5    0.0560  
  7 AT    Austria        6                       43.2    0.0556  
  8 AT    Austria        7                      125.     0.161   
  9 AT    Austria        8                      251.     0.323   
 10 AT    Austria        9                      198.     0.255   
 11 AT    Austria        10 - Extremely happy    88.3    0.114   
 12 BE    Belgium        0 - Extremely unhappy    1.73   0.00177 
 13 BE    Belgium        1                        1.16   0.00118 
 14 BE    Belgium        2                        6.60   0.00673 
 15 BE    Belgium        3                       15.0    0.0153  
 16 BE    Belgium        4                       15.2    0.0155  
 17 BE    Belgium        5                       45.8    0.0467  
 18 BE    Belgium        6                       63.9    0.0651  
 19 BE    Belgium        7                      191.     0.195   
 20 BE    Belgium        8                      362.     0.369   
 21 BE    Belgium        9                      199.     0.203   
 22 BE    Belgium        10 - Extremely happy    79.6    0.0812  
 23 BG    Bulgaria       0 - Extremely unhappy   11.1    0.0202  
 24 BG    Bulgaria       1                        4.70   0.00850 
 25 BG    Bulgaria       2                       15.9    0.0287  
 26 BG    Bulgaria       3                       24.4    0.0442  
 27 BG    Bulgaria       4                       32.2    0.0582  
 28 BG    Bulgaria       5                       98.8    0.179   
 29 BG    Bulgaria       6                       78.1    0.141   
 30 BG    Bulgaria       7                      116.     0.210   
 31 BG    Bulgaria       8                      100.     0.182   
 32 BG    Bulgaria       9                       29.4    0.0533  
 33 BG    Bulgaria       10 - Extremely happy    41.6    0.0753  
 34 CH    Switzerland    0 - Extremely unhappy    1.13   0.00151 
 35 CH    Switzerland    1                        0.516  0.000691
 36 CH    Switzerland    2                        2.82   0.00377 
 37 CH    Switzerland    3                        8.33   0.0112  
 38 CH    Switzerland    4                        7.30   0.00977 
 39 CH    Switzerland    5                       27.4    0.0366  
 40 CH    Switzerland    6                       24.0    0.0321  
 41 CH    Switzerland    7                      104.     0.139   
 42 CH    Switzerland    8                      251.     0.336   
 43 CH    Switzerland    9                      205.     0.275   
 44 CH    Switzerland    10 - Extremely happy   116.     0.155   
 45 CY    Cyprus         0 - Extremely unhappy    0.688  0.00899 
 46 CY    Cyprus         1                        0.740  0.00967 
 47 CY    Cyprus         2                        0.969  0.0127  
 48 CY    Cyprus         3                        2.00   0.0261  
 49 CY    Cyprus         4                        3.04   0.0397  
 50 CY    Cyprus         5                       10.9    0.143   
 51 CY    Cyprus         6                        6.55   0.0857  
 52 CY    Cyprus         7                       16.7    0.218   
 53 CY    Cyprus         8                       19.6    0.256   
 54 CY    Cyprus         9                        6.81   0.0890  
 55 CY    Cyprus         10 - Extremely happy     8.51   0.111   
 56 DE    Germany        0 - Extremely unhappy    8.11   0.00112 
 57 DE    Germany        1                       40.3    0.00557 
 58 DE    Germany        2                       74.5    0.0103  
 59 DE    Germany        3                      164.     0.0227  
 60 DE    Germany        4                      130.     0.0180  
 61 DE    Germany        5                      525.     0.0725  
 62 DE    Germany        6                      583.     0.0805  
 63 DE    Germany        7                     1122.     0.155   
 64 DE    Germany        8                     2361.     0.326   
 65 DE    Germany        9                     1396.     0.193   
 66 DE    Germany        10 - Extremely happy   833.     0.115   
 67 EE    Estonia        0 - Extremely unhappy    0.369  0.00325 
 68 EE    Estonia        1                        0.328  0.00288 
 69 EE    Estonia        2                        1.02   0.00899 
 70 EE    Estonia        3                        2.98   0.0262  
 71 EE    Estonia        4                        4.03   0.0354  
 72 EE    Estonia        5                       11.8    0.103   
 73 EE    Estonia        6                        8.19   0.0720  
 74 EE    Estonia        7                       24.4    0.215   
 75 EE    Estonia        8                       31.4    0.276   
 76 EE    Estonia        9                       18.3    0.160   
 77 EE    Estonia        10 - Extremely happy    11.1    0.0973  
 78 ES    Spain          0 - Extremely unhappy   10.2    0.00247 
 79 ES    Spain          1                        2.13   0.000513
 80 ES    Spain          2                       21.9    0.00527 
 81 ES    Spain          3                       41.0    0.00989 
 82 ES    Spain          4                       56.8    0.0137  
 83 ES    Spain          5                      213.     0.0514  
 84 ES    Spain          6                      312.     0.0753  
 85 ES    Spain          7                      798.     0.192   
 86 ES    Spain          8                     1228.     0.296   
 87 ES    Spain          9                      773.     0.186   
 88 ES    Spain          10 - Extremely happy   694.     0.167   
 89 FI    Finland        0 - Extremely unhappy    0.393  0.000833
 90 FI    Finland        1                        0.396  0.000840
 91 FI    Finland        2                        3.31   0.00703 
 92 FI    Finland        3                        7.50   0.0159  
 93 FI    Finland        4                        9.12   0.0194  
 94 FI    Finland        5                       11.6    0.0246  
 95 FI    Finland        6                       17.5    0.0370  
 96 FI    Finland        7                       61.4    0.130   
 97 FI    Finland        8                      163.     0.345   
 98 FI    Finland        9                      147.     0.312   
 99 FI    Finland        10 - Extremely happy    50.9    0.108   
100 FR    France         0 - Extremely unhappy   28.0    0.00499 
101 FR    France         1                        3.74   0.000665
102 FR    France         2                       22.7    0.00404 
103 FR    France         3                       67.2    0.0119  
104 FR    France         4                      115.     0.0205  
105 FR    France         5                      589.     0.105   
106 FR    France         6                      497.     0.0884  
107 FR    France         7                     1262.     0.225   
108 FR    France         8                     1603.     0.285   
109 FR    France         9                      860.     0.153   
110 FR    France         10 - Extremely happy   574.     0.102   
111 GB    United Kingdom 0 - Extremely unhappy   47.2    0.00848 
112 GB    United Kingdom 1                       22.4    0.00403 
113 GB    United Kingdom 2                       68.1    0.0122  
114 GB    United Kingdom 3                       86.2    0.0155  
115 GB    United Kingdom 4                      184.     0.0331  
116 GB    United Kingdom 5                      349.     0.0627  
117 GB    United Kingdom 6                      482.     0.0865  
118 GB    United Kingdom 7                     1098.     0.197   
119 GB    United Kingdom 8                     1583.     0.284   
120 GB    United Kingdom 9                      892.     0.160   
121 GB    United Kingdom 10 - Extremely happy   759.     0.136   
122 GR    Greece         0 - Extremely unhappy    0.838  0.000930
123 GR    Greece         1                        5.18   0.00575 
124 GR    Greece         2                        6.31   0.00700 
125 GR    Greece         3                       25.3    0.0281  
126 GR    Greece         4                       33.8    0.0375  
127 GR    Greece         5                      107.     0.119   
128 GR    Greece         6                      134.     0.149   
129 GR    Greece         7                      243.     0.270   
130 GR    Greece         8                      259.     0.288   
131 GR    Greece         9                       78.4    0.0871  
132 GR    Greece         10 - Extremely happy     7.27   0.00807 
133 HR    Croatia        0 - Extremely unhappy    0.374  0.00114 
134 HR    Croatia        1                        0.951  0.00289 
135 HR    Croatia        2                        4.27   0.0130  
136 HR    Croatia        3                        5.90   0.0180  
137 HR    Croatia        4                       11.1    0.0338  
138 HR    Croatia        5                       34.5    0.105   
139 HR    Croatia        6                       26.1    0.0793  
140 HR    Croatia        7                       57.0    0.173   
141 HR    Croatia        8                       81.5    0.248   
142 HR    Croatia        9                       47.8    0.145   
143 HR    Croatia        10 - Extremely happy    59.2    0.180   
144 HU    Hungary        0 - Extremely unhappy    3.46   0.00423 
145 HU    Hungary        1                        3.18   0.00389 
146 HU    Hungary        2                       15.7    0.0192  
147 HU    Hungary        3                       22.0    0.0269  
148 HU    Hungary        4                       27.1    0.0331  
149 HU    Hungary        5                       82.1    0.100   
150 HU    Hungary        6                       96.5    0.118   
151 HU    Hungary        7                      161.     0.197   
152 HU    Hungary        8                      194.     0.238   
153 HU    Hungary        9                      104.     0.127   
154 HU    Hungary        10 - Extremely happy   109.     0.133   
155 IE    Ireland        0 - Extremely unhappy    0.502  0.00118 
156 IE    Ireland        1                        0.388  0.000912
157 IE    Ireland        2                        3.11   0.00732 
158 IE    Ireland        3                        4.51   0.0106  
159 IE    Ireland        4                        8.92   0.0210  
160 IE    Ireland        5                       20.2    0.0474  
161 IE    Ireland        6                       41.2    0.0969  
162 IE    Ireland        7                       80.0    0.188   
163 IE    Ireland        8                      133.     0.314   
164 IE    Ireland        9                       81.9    0.193   
165 IE    Ireland        10 - Extremely happy    51.1    0.120   
166 IL    Israel         0 - Extremely unhappy    8.19   0.0122  
167 IL    Israel         1                        4.11   0.00611 
168 IL    Israel         2                        5.27   0.00783 
169 IL    Israel         3                       11.6    0.0173  
170 IL    Israel         4                       17.3    0.0258  
171 IL    Israel         5                       38.9    0.0578  
172 IL    Israel         6                       76.6    0.114   
173 IL    Israel         7                      143.     0.212   
174 IL    Israel         8                      183.     0.271   
175 IL    Israel         9                      102.     0.151   
176 IL    Israel         10 - Extremely happy    83.6    0.124   
177 IS    Iceland        0 - Extremely unhappy    0.0496 0.00157 
178 IS    Iceland        2                        0.183  0.00579 
179 IS    Iceland        3                        0.765  0.0242  
180 IS    Iceland        4                        0.785  0.0249  
181 IS    Iceland        5                        1.15   0.0365  
182 IS    Iceland        6                        1.53   0.0484  
183 IS    Iceland        7                        4.81   0.152   
184 IS    Iceland        8                       10.7    0.339   
185 IS    Iceland        9                        7.98   0.253   
186 IS    Iceland        10 - Extremely happy     3.61   0.114   
187 IT    Italy          0 - Extremely unhappy   31.2    0.00607 
188 IT    Italy          1                       32.7    0.00637 
189 IT    Italy          2                       52.6    0.0102  
190 IT    Italy          3                      126.     0.0245  
191 IT    Italy          4                      185.     0.0361  
192 IT    Italy          5                      456.     0.0889  
193 IT    Italy          6                      897.     0.175   
194 IT    Italy          7                     1382.     0.269   
195 IT    Italy          8                     1300.     0.253   
196 IT    Italy          9                      432.     0.0843  
197 IT    Italy          10 - Extremely happy   236.     0.0459  
198 LT    Lithuania      0 - Extremely unhappy    1.92   0.00791 
199 LT    Lithuania      1                        0.533  0.00220 
200 LT    Lithuania      2                        2.53   0.0104  
201 LT    Lithuania      3                        4.50   0.0186  
202 LT    Lithuania      4                        8.65   0.0357  
203 LT    Lithuania      5                       21.7    0.0894  
204 LT    Lithuania      6                       19.0    0.0785  
205 LT    Lithuania      7                       41.0    0.169   
206 LT    Lithuania      8                       64.1    0.264   
207 LT    Lithuania      9                       42.9    0.177   
208 LT    Lithuania      10 - Extremely happy    35.5    0.147   
209 LV    Latvia         0 - Extremely unhappy    1.15   0.00731 
210 LV    Latvia         1                        1.24   0.00786 
211 LV    Latvia         2                        1.90   0.0121  
212 LV    Latvia         3                        3.93   0.0250  
213 LV    Latvia         4                        6.95   0.0442  
214 LV    Latvia         5                       24.6    0.157   
215 LV    Latvia         6                       13.0    0.0829  
216 LV    Latvia         7                       33.2    0.211   
217 LV    Latvia         8                       40.1    0.255   
218 LV    Latvia         9                       17.8    0.113   
219 LV    Latvia         10 - Extremely happy    13.3    0.0845  
220 ME    Montenegro     0 - Extremely unhappy    0.165  0.00327 
221 ME    Montenegro     1                        0.231  0.00459 
222 ME    Montenegro     2                        0.456  0.00906 
223 ME    Montenegro     3                        0.868  0.0172  
224 ME    Montenegro     4                        3.70   0.0735  
225 ME    Montenegro     5                       14.4    0.286   
226 ME    Montenegro     6                        6.66   0.132   
227 ME    Montenegro     7                        6.61   0.131   
228 ME    Montenegro     8                        7.07   0.140   
229 ME    Montenegro     9                        3.85   0.0765  
230 ME    Montenegro     10 - Extremely happy     6.34   0.126   
231 NL    Netherlands    0 - Extremely unhappy    8.39   0.00557 
232 NL    Netherlands    2                        1.79   0.00119 
233 NL    Netherlands    3                        4.88   0.00324 
234 NL    Netherlands    4                       16.3    0.0108  
235 NL    Netherlands    5                       39.9    0.0265  
236 NL    Netherlands    6                       77.5    0.0514  
237 NL    Netherlands    7                      262.     0.174   
238 NL    Netherlands    8                      639.     0.424   
239 NL    Netherlands    9                      364.     0.242   
240 NL    Netherlands    10 - Extremely happy    92.7    0.0615  
241 NO    Norway         1                        0.286  0.000627
242 NO    Norway         2                        3.45   0.00755 
243 NO    Norway         3                        6.99   0.0153  
244 NO    Norway         4                        6.82   0.0150  
245 NO    Norway         5                       20.1    0.0441  
246 NO    Norway         6                       29.5    0.0646  
247 NO    Norway         7                       76.4    0.167   
248 NO    Norway         8                      141.     0.309   
249 NO    Norway         9                      109.     0.240   
250 NO    Norway         10 - Extremely happy    62.3    0.136   
251 PL    Poland         0 - Extremely unhappy    4.19   0.00136 
252 PL    Poland         1                        9.30   0.00301 
253 PL    Poland         2                       34.9    0.0113  
254 PL    Poland         3                       61.4    0.0199  
255 PL    Poland         4                       59.2    0.0192  
256 PL    Poland         5                      245.     0.0795  
257 PL    Poland         6                      292.     0.0946  
258 PL    Poland         7                      541.     0.175   
259 PL    Poland         8                      850.     0.275   
260 PL    Poland         9                      464.     0.150   
261 PL    Poland         10 - Extremely happy   524.     0.170   
262 PT    Portugal       0 - Extremely unhappy    4.27   0.00469 
263 PT    Portugal       1                        5.53   0.00608 
264 PT    Portugal       2                       10.6    0.0116  
265 PT    Portugal       3                       16.8    0.0184  
266 PT    Portugal       4                       25.9    0.0285  
267 PT    Portugal       5                      107.     0.117   
268 PT    Portugal       6                       96.1    0.106   
269 PT    Portugal       7                      182.     0.200   
270 PT    Portugal       8                      244.     0.268   
271 PT    Portugal       9                      121.     0.133   
272 PT    Portugal       10 - Extremely happy    97.9    0.108   
273 RS    Serbia         0 - Extremely unhappy    7.09   0.0125  
274 RS    Serbia         1                        4.51   0.00796 
275 RS    Serbia         2                        6.00   0.0106  
276 RS    Serbia         3                       11.1    0.0195  
277 RS    Serbia         4                       17.7    0.0312  
278 RS    Serbia         5                       61.7    0.109   
279 RS    Serbia         6                       42.8    0.0755  
280 RS    Serbia         7                      101.     0.178   
281 RS    Serbia         8                      143.     0.252   
282 RS    Serbia         9                       71.5    0.126   
283 RS    Serbia         10 - Extremely happy   101.     0.179   
284 SE    Sweden         0 - Extremely unhappy    3.28   0.00379 
285 SE    Sweden         1                        3.81   0.00439 
286 SE    Sweden         2                        4.49   0.00518 
287 SE    Sweden         3                        9.32   0.0108  
288 SE    Sweden         4                       16.4    0.0189  
289 SE    Sweden         5                       41.3    0.0477  
290 SE    Sweden         6                       73.4    0.0847  
291 SE    Sweden         7                      160.     0.185   
292 SE    Sweden         8                      289.     0.333   
293 SE    Sweden         9                      185.     0.213   
294 SE    Sweden         10 - Extremely happy    81.0    0.0934  
295 SI    Slovenia       0 - Extremely unhappy    0.399  0.00224 
296 SI    Slovenia       1                        0.674  0.00378 
297 SI    Slovenia       2                        1.00   0.00563 
298 SI    Slovenia       3                        2.85   0.0160  
299 SI    Slovenia       4                        3.70   0.0208  
300 SI    Slovenia       5                        9.76   0.0548  
301 SI    Slovenia       6                       12.5    0.0701  
302 SI    Slovenia       7                       30.1    0.169   
303 SI    Slovenia       8                       56.6    0.318   
304 SI    Slovenia       9                       34.7    0.195   
305 SI    Slovenia       10 - Extremely happy    26.0    0.146   
306 SK    Slovakia       0 - Extremely unhappy    2.81   0.00621 
307 SK    Slovakia       1                        1.61   0.00355 
308 SK    Slovakia       2                        6.72   0.0149  
309 SK    Slovakia       3                       26.3    0.0580  
310 SK    Slovakia       4                       31.1    0.0687  
311 SK    Slovakia       5                       56.9    0.126   
312 SK    Slovakia       6                       50.8    0.112   
313 SK    Slovakia       7                       87.8    0.194   
314 SK    Slovakia       8                       92.7    0.205   
315 SK    Slovakia       9                       50.4    0.111   
316 SK    Slovakia       10 - Extremely happy    45.8    0.101   
317 UA    Ukraine        0 - Extremely unhappy  106.     0.0312  
318 UA    Ukraine        1                       47.5    0.0140  
319 UA    Ukraine        2                      112.     0.0329  
320 UA    Ukraine        3                      189.     0.0556  
321 UA    Ukraine        4                      179.     0.0526  
322 UA    Ukraine        5                      785.     0.231   
323 UA    Ukraine        6                      288.     0.0847  
324 UA    Ukraine        7                      442.     0.130   
325 UA    Ukraine        8                      528.     0.155   
326 UA    Ukraine        9                      254.     0.0746  
327 UA    Ukraine        10 - Extremely happy   472.     0.139   

Exercise 3: calculate distribution of happiness level by country

happy_dist_country <-
  ess_des |>
  filter(!is.na(Happy)) |>
  mutate(
    Happy_factor = factor(
      Happy,
      levels = 0:10,
      labels = c(
        "0 - Extremely unhappy", 1:9, "10 - Extremely happy"
      )
    )
  ) |>
  group_by(interact(cntry, Country), Happy_factor) |>
  summarize(
    n = survey_total(vartype = NULL),
    p = survey_mean(vartype = NULL)
    ) |>
  ungroup()

happy_dist_country |>
  print(n = Inf)

Exercise 4: identify the happiest and least happy countries

To keep the chart readable, identify the top and bottom 4 based on mean happiness (8 total, as in the reference chart).

[1] "Switzerland" "Finland"     "Norway"      "Netherlands"
[5] "Bulgaria"    "Ukraine"     "Montenegro"  "Slovakia"   

Exercise 4: identify the happiest and least happy countries

n_countries <- 4

top_bottom_countries <-
  happy_by_country |>
  slice_max(Happy_mean, n = n_countries) |>
  bind_rows(
    happy_by_country |> slice_min(Happy_mean, n = n_countries)
  ) |>
  pull(Country)

Exercise 5: make bar chart with country subset ordered by mean

Hint: use this fill scale for the diverging 11-point Likert palette

scale_fill_brewer(palette = "RdBu", direction = -1, name = NULL)

Exercise 5: make bar chart with country subset ordered by mean

happy_likert <-
  happy_dist_country |>
  left_join(happy_by_country, by = "Country") |>
  filter(Country %in% top_bottom_countries) |>
  mutate(Label = fct_reorder(paste(cntry, "-", Country), Happy_mean))

ggplot(happy_likert, aes(y = Label, x = p, fill = Happy_factor)) +
  # reverse = TRUE keeps "0 - Extremely unhappy" on the left and
  # "10 - Extremely happy" on the right, matching the legend order
  geom_col(position = position_fill(reverse = TRUE)) +
  scale_fill_brewer(palette = "RdBu", direction = -1, name = NULL) +
  scale_x_continuous(labels = scales::percent) +
  labs(
    title = "How happy are you?",
    subtitle = glue::glue("Top and bottom {n_countries} countries by weighted mean"),
    x = NULL,
    y = NULL
  ) +
  theme_light() +
  theme(legend.position = "bottom")

Map survey estimates

  • Country is a natural domain for ESS analysis
  • Choropleth maps make cross-country patterns easier to spot than a table
  • Builds on two earlier pieces: survey-weighted estimation (srvyr) + country shapes (sf) + ggplot2

Exercise 6: join country shapes to mean estimates

Get a base map from {tmap} using the object World and join the mean estimates on. Crop the map to the extent of ESS using this code:

dat_sf |>
  st_crop(
    st_bbox(c(xmin = -10, ymin = 32, xmax = 36, ymax = 70), crs = 4326) |>
      st_transform(3035)
  )

Exercise 6: join country shapes to mean estimates

happy_shape <-
  World |>
  full_join(happy_by_country, by = c("name" = "Country")) |>
  st_transform(3035) |>
  st_crop(
    st_bbox(c(xmin = -10, ymin = 32, xmax = 36, ymax = 70), crs = 4326) |>
      st_transform(3035)
  )

Exercise 7: map colored by Happy

Exercise 7: map colored by Happy

happy_shape |>
  ggplot() +
  geom_sf(aes(fill = Happy_mean), color = "darkgrey") +
  geom_sf_text(
    data = happy_shape |> filter(!is.na(Happy_mean)),
    aes(label = iso_a3),
    size = 3
  ) +
  scale_fill_distiller(
    palette = "Blues",
    direction = 1,
    na.value = "lightgrey",
    name = "Mean happiness\n(0-10 scale)"
  ) +
  labs(x = NULL, y = NULL) +
  theme_light()

Closing

Additional resources

Our website

  • How to get our book
  • R package with data
  • More tutorials

Our book

  • Descriptive analysis
  • Statistical testing
  • Modeling
  • Complete vignettes

Q & A

References

European Social Survey European Research Infrastructure (ESS ERIC). 2024a. ESS11 Integrated File, Edition 4.2 [Data Set]. https://doi.org/10.21338/ess11e04_2.
European Social Survey European Research Infrastructure (ESS ERIC). 2024b. European Social Survey European Research Infrastructure (ESS ERIC) (2026) ESS Round 11 - 2023. Social Inequalities in Health, Gender in Contemporary Europe. https://doi.org/10.21338/ESS11-2023.
Freedman Ellis, Greg, and Ben Schneider. 2026. srvyr: ’dplyr’-Like Syntax for Summary Statistics of Survey Data. https://doi.org/10.32614/CRAN.package.srvyr.
Lumley, Thomas. 2026. survey: Analysis of Complex Survey Samples. https://doi.org/10.32614/CRAN.package.survey.
Zimmer, Stephanie, Rebecca Powell, and Isabella Velásquez. 2024. Exploring Complex Survey Data Analysis Using R: A Tidy Introduction with {srvyr} and {survey}. CRC Press.

Supplementary material

Working with pipes in {survey}

Magrittr pipe (%>%)

  • dot notation
design_object %>% 
  svyglm(design = ., y ~ x)

Base R pipe (|>)

  • placeholder
design_object |> 
  svyglm(design = _, y ~ x)
  • anonymous (lambda) functions
design_object |> 
  (\(.) 
   svyglm(design = ., y ~ x)
  )()

Accessing ESS data - via API

  1. Create an ESS account and get your user ID

  2. Open R environ file

usethis::edit_r_environ()
  1. Add your user ID to R environ
ESS_USERID="12345678-1234-1234-1234-12345678900"
  1. Restart your R session

  2. Load the ESS data into R

url <- glue::glue("https://api.ess.sikt.no/v1/data/dataFile/10.21338/ess11e04_2?userId={Sys.getenv('ESS_USERID')}")
ess_in <- arrow::read_parquet(url)

Replicate weights overview

Replicate weights are another method to estimate variability. In general, they are constructed by:

  1. Divide the sample into subsample replicates that mirror the design of the sample
  2. Calculate weights for each replicate using the same procedures for the full-sample weight (i.e., nonresponse and post-stratification)
  3. Calculate estimates for each replicate using the same method as the full-sample estimate
  4. Calculate the estimated variance, which is proportional to the variance of the replicate estimates

Common replicate weight methods

  • Balanced repeated replication (BRR)
  • Fay’s BRR
  • Jackknife
  • Bootstrap