{"id":111505,"date":"2020-04-13T16:59:00","date_gmt":"2020-04-13T21:59:00","guid":{"rendered":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/decoded\/\/\/analyzing-international-survey-data-with-the-pewmethods-r-package\/"},"modified":"2024-04-14T04:10:36","modified_gmt":"2024-04-14T09:10:36","slug":"analyzing-international-survey-data-with-the-pewmethods-r-package","status":"publish","type":"decoded","link":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/decoded\/2020\/04\/13\/analyzing-international-survey-data-with-the-pewmethods-r-package\/","title":{"rendered":"Analyzing international survey data with the pewmethods R package"},"content":{"rendered":"\n<figure class=\"wp-block-image size-640-wide\"><a rel=\"attachment wp-att-125913\" href=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/decoded\/2013\/01\/analyzing-international-survey-data-with-the-pewmethods-r-package\/2020-04-13_decoded_featured-png\/\"><img data-dominant-color=\"7f7688\" data-has-transparency=\"false\" style=\"--dominant-color: #7f7688;\" loading=\"lazy\" decoding=\"async\"  srcset=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?resize=480,270 480w, https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?resize=782,440 782w, https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?resize=960,540 960w, https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?resize=1200,675 1200w, https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?resize=1400,788 1400w\" sizes=\"(max-width: 480px) 480px, (max-width: 782px) 782px, 640px\" height=\"360\" width=\"640\" src=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?w=640\" alt=\"\" class=\"wp-image-125913 not-transparent\" \/><\/a><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"9a07\"><em>(Related posts:&nbsp;<\/em><a href=\"https:\/\/medium.com\/pew-research-center-decoded\/introducing-pewmethods-an-r-package-for-working-with-survey-data-97601a250a46\"><em>Introducing pewmethods: An R package for working with survey data<\/em><\/a>,&nbsp;<a href=\"https:\/\/medium.com\/pew-research-center-decoded\/exploring-survey-data-with-the-pewmethods-r-package-198c4eb9d1af\"><em>Exploring survey data with the pewmethods R package<\/em><\/a><em>&nbsp;and&nbsp;<\/em><a href=\"https:\/\/medium.com\/pew-research-center-decoded\/weighting-survey-data-with-the-pewmethods-r-package-d040afb0d2c2\"><em>Weighting survey data with the pewmethods R package<\/em><\/a><em>)<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"b1a4\">Pew Research Center makes most of its survey data&nbsp;<a href=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/short-reads\/2018\/03\/09\/how-to-access-pew-research-center-survey-data\/\" rel=\"noreferrer noopener\" target=\"_blank\">available for free online<\/a>. This includes datasets from the annual Global Attitudes Survey, a poll that asks adults in many countries about issues ranging from politics to economic conditions. These files are generally available for download in IBM\u2019s SPSS .sav format. But even without access to SPSS, any student or researcher can analyze these multi-level datasets using the free, open-source&nbsp;<a href=\"https:\/\/www.r-project.org\/\" rel=\"noreferrer noopener\" target=\"_blank\">R statistical software platform<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"f299\">This post walks through an analysis of data from the Center\u2019s spring 2017 Global Attitudes Survey, which&nbsp;<a href=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/global\/dataset\/spring-2017-survey-data\/\" rel=\"noreferrer noopener\" target=\"_blank\">you can access here<\/a>. (You will need to create a free account before downloading.)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"7089\">Once you have the file saved it in a handy location, you can start analyzing the data with the Center\u2019s new pewmethods R package. This package allows you to generate country-level crosstabs in the same way that researchers at the Center conduct their analyses. You can read more about&nbsp;<a href=\"https:\/\/medium.com\/pew-research-center-decoded\/introducing-pewmethods-an-r-package-for-working-with-survey-data-97601a250a46\">our new R package here<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"7952\">The pewmethods package is hosted on the Center\u2019s&nbsp;<a href=\"https:\/\/github.com\/pewresearch\/\" rel=\"noreferrer noopener\" target=\"_blank\">Github page<\/a>. You can get pewmethods by first installing the devtools package:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>install.packages(\u201cdevtools\u201d)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"6815\">Next, run the following line of code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>install_github(\u201cpewresearch\/pewmethods\u201d)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"6602\">We\u2019ll also use the tidyverse package, which lets us open the data from the .sav extension as well as assists in recoding variables and filtering the data. My colleague, Nick Hatley, has written&nbsp;<a href=\"https:\/\/medium.com\/pew-research-center-decoded\/using-tidyverse-tools-with-pew-research-center-survey-data-in-r-bdfe61de0909\">a great intro on using R and tidyverse<\/a>&nbsp;to analyze Center survey data. Later on, we\u2019ll make a map and an opposing bar chart, so we should load the required packages for those at this point as well. You\u2019ll need to install these packages first in order to run the code in this post. Even if you have already installed them, you can update them by running the first line (install.packages\u2026) in the below code block. We load the packages into our R session with the library() function.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#install.packages(c(\u201ctidyverse\u201d, \u201crworldmap\u201d, \u201cggrepel\u201d))<br>library(pewmethods)<br>library(tidyverse)<br>library(rworldmap)<br>library(ggrepel)# You will need to adjust the file path in the parentheses below depending on where you save the downloaded dataset<br>gap_rd &lt;- haven::read_sav(\u201c2017 Topline.sav\u201d)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"c3dd\">This dataset has more than 800 variables and 40,000 rows. For this explainer, I\u2019ll examine two economically focused questions from the 2017 survey, published in the report, \u201c<a href=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/global\/2017\/06\/05\/global-publics-more-upbeat-about-the-economy\/\" rel=\"noreferrer noopener\" target=\"_blank\">Global Publics More Upbeat About the Economy<\/a>.\u201d Since I\u2019m just looking at two survey questions here, I\u2019ll only need a handful of variables. We can narrow down the dataset to the variables of interest using the `select` function.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>gap2017 &lt;- gap_rd %&gt;%<br>  select(<br>    Country,  # country variable<br>    econ_sit,  # current economic situation in your country<br>    children_betteroff2,  # will children be better off\/worse off than parents<br>    weight     # survey weights - very important!<br>  )%&gt;%<br>  haven::as_factor()<\/code><\/pre>\n\n\n\n<h3 data-is-section=\"true\" data-wp-context=\"{&quot;id&quot;:&quot;d6c4&quot;}\" data-wp-interactive=\"{&quot;namespace&quot;:&quot;prc-block\\\/table-of-contents&quot;}\" class=\"wp-block-heading\" id=\"d6c4\">Rearrange and explore the data<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"827d\">Now we have a dataset that is much more user friendly, with six variables and around 42,000 observations. We can identify the countries included in the survey, find the exact question wording based on the SPSS labels, and get country-level estimates for questions of interest.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"7b44\">Here, we will look at two questions:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"550e\">1. How did people view their country\u2019s economic situation in 2017?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"e640\">2. Did people think that children in their country would be better or worse off than their parents?<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; unique(as.character(gap2017$Country))  # 38 countries<br> &#091;1] \"United States\" \"Mexico\" \"Canada\" \"Russia\" \"South Korea\"<br> &#091;6] \"United Kingdom\" \"France\" \"Germany\" \"Netherlands\" \"Spain\"<br>&#091;11] \"Sweden\" \"Poland\" \"Greece\" \"Hungary\" \"Italy\" <br>&#091;16] \"Japan\" \"Australia\" \"India\" \"Indonesia\" \"Philippines\"<br>&#091;21] \"Israel\" \"Turkey\" \"Argentina\" \"Brazil\" \"Chile\"<br>&#091;26] \"Colombia\" \"Venezuela\" \"Ghana\" \"Kenya\" \"Nigeria\"<br>&#091;31] \"South Africa\" \"Senegal\" \"Tunisia\" \"Vietnam\" \"Jordan\"<br>&#091;36] \"Lebanon\" \"Tanzania\" \"Peru\"&gt; get_spss_label(gap2017, c(\"econ_sit\", \"children_betteroff2\"))<br>&#091;1] \"Q5. Now thinking about our economic situation, how would you describe the current economic situation in (survey country) \u2014 is it very good, somewhat good, somewhat bad or very bad?\"<br>&#091;2] \"Q8. When children today in (survey country) grow up, do you think they will be better off or worse off financially than their parents?\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"aa16\">With the launch of the pewmethods package, we can easily convert the data from individual- to country-level data, first with the economic situation question. The line of code below tells R to look at the econ_sit variable in the gap2017 dataframe, apply survey weights called weight, group the data by the country2 variable, and round it to the nearest whole number. The resulting object will be in a&nbsp;<a href=\"https:\/\/www.theanalysisfactor.com\/wide-and-long-data\/\" rel=\"noreferrer noopener\" target=\"_blank\">wide format<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; econ_data_wide &lt;- get_totals(\"econ_sit\", gap2017, wt = \"weight\", by = \"Country\", na.rm = T, digits = 0)<br>&gt; head(econ_data_wide)<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/max\/1400\/1*Ho6I7Fs13NHhpHLEuUI0pA.png\" alt=\"\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"392c\">For analysis and graphing purposes, it might be easier to have the data in a long format instead. We can use the gather function from the tidyverse package to transpose the data, renaming the country variable to \u201ccountry\u201d and the percent values \u201ceconomy.\u201d<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; econ_data_long &lt;- econ_data_wide %&gt;%<br>  gather(country, economy, -one_of(\"econ_sit\", \"weight_name\"), <br>  factor_key = T)<br>&gt; head(econ_data_long)<br>                  econ_sit weight_name   country economy<br>1                Very good      weight Argentina       5<br>2            Somewhat good      weight Argentina      18<br>3             Somewhat bad      weight Argentina      44<br>4                 Very bad      weight Argentina      29<br>5 Don\u2019t know (DO NOT READ)      weight Argentina       3<br>6    Refused (DO NOT READ)      weight Argentina       1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"4b99\">The global attitudes team at Pew Research Center (which I\u2019m part of) usually collapses these into \u201cgood\u201d and \u201cbad\u201d categories by adding the rounded totals for very\/somewhat good and very\/somewhat bad. One way to replicate this is below, with a preview of the first few lines of the new object. The spread() function is used to shape the dataset from long back to wide.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>econ_sit_collapse &lt;- econ_data_long %&gt;%<br>mutate(econ_eval = case_when(<br>  econ_sit == \"Very good\" ~ \"Good\",<br>  econ_sit == \"Somewhat good\" ~ \"Good\", <br>  econ_sit == \"Somewhat bad\" ~ \"Bad\",<br>  econ_sit == \"Very bad\" ~ \"Bad\",<br>  TRUE ~ \"DK\/Refused\")  # parenthesis closes call to `case_when`<br>) %&gt;% # parenthesis before pipe closes call to `mutate`<br>  group_by(country, econ_eval) %&gt;%<br>  summarise(share = sum(economy))<br>final_econ &lt;- econ_sit_collapse %&gt;% spread(econ_eval, share)&gt; head(final_econ&#091;c(\"country\", \"Good\", \"Bad\", \"DK\/Refused\")])<br># A tibble: 6 x 4<br># Groups:   country &#091;38]<br>  country    Good   Bad `DK\/Refused`<br>  <em>&lt;fct&gt;<\/em>     <em>&lt;dbl&gt;<\/em> <em>&lt;dbl&gt;<\/em>        <em>&lt;dbl&gt;<\/em><br>1 Argentina    23    73            4<br>2 Australia    60    40            1<br>3 Brazil       15    82            3<br>4 Canada       59    38            2<br>5 Chile        45    54            1<br>6 Colombia     34    65            1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"3a96\">The 2017 report&nbsp;<a href=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/global\/2017\/06\/05\/global-publics-more-upbeat-about-the-economy\/pg_17-06-01_world-economy_web\/\" rel=\"noreferrer noopener\" target=\"_blank\">features a map<\/a>&nbsp;of the data showing the share of adults in each country who said the economic situation was good. We can create a similar version below with the rworldmap package, which lets us create a map and adjust the colors in more customized ways.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"511b\">We\u2019ll recode the economy data into categories to mimic the color scheme in the report map (this time on a green\/blue scale), turn it into a factor, and then re-level everything to keep it in the order we want, instead of the default alphabetical order. I also added colors from the Center\u2019s style guide and a title to the chart, using hexadecimal values to get an exact color match and adding \u201cn\u201d to the title make it break over two lines.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># recode econ_sit into categorical variable for map<br>final_econ &lt;- final_econ %&gt;%<br>  mutate(econ_good_cat = case_when(<br>    Good &lt; 20 ~ \"&lt;20%\",<br>    Good %in% 20:34 ~ \"20-34\",<br>    Good %in% 35:49 ~ \"35-49\",<br>    Good %in% 50:64 ~ \"50-64\",<br>    Good %in% 65:80 ~ \"65-80\",<br>    Good &gt; 80 ~ \"&gt;80%\") %&gt;%<br>      fct_relevel(\"&lt;20%\", \"20-34\", \"35-49\", \"50-64\", \"65-80\", \"&gt;80%\")<br>      ) %&gt;%<br>  ungroupsPDF &lt;- joinCountryData2Map(final_econ,<br>                            joinCode = \"NAME\",<br>                            nameJoinColumn = \"country\")mapCountryData(sPDF,<br>               nameColumnToPlot = \"econ_good_cat\",<br>               catMethod = \"categorical\",<br>               colourPalette = c (\"#1F497D\", \"#8DB5E2\", \"#C5D9F1\", \"#C4CA8A\", \"#949D48\", \"#707636\"),<br>               mapTitle = \"% who say the current economic nsituation in our country is good, 2017\",<br>               missingCountryCol = \"#F2F2F2\")Output:<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/max\/1222\/1*xbM450TgsuioQKCWioWehw.png\" alt=\"\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"d372\">We can do similar analyses with other variables in the 2017 Global Attitudes Survey dataset. Say, for example, that a researcher is interested in how Europeans view the&nbsp;<a href=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/global\/2017\/06\/05\/2-public-divided-on-prospects-for-the-next-generation\/\" rel=\"noreferrer noopener\" target=\"_blank\">prospects of the next generation<\/a>. The survey includes a question that asks whether respondents think children in their country will be better or worse off financially than their parents. We can view the positive and negative sides of the question for the European countries surveyed and display the results in a chart.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"b5b4\">For a Europe-only graphic, we\u2019ll first have to filter our dataset to European countries. Again, using the get_totals function, we can calculate weighted frequencies by country.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>gap2017_EU &lt;- gap2017 %&gt;% <br>  filter(Country %in% c(\"United Kingdom\", \"France\", \"Germany\", \"Netherlands\",\"Spain\", \"Sweden\", \"Poland\", \"Greece\", \"Hungary\", \"Italy\"))children_data_wide &lt;- get_totals(\"children_betteroff2\", gap2017_EU, wt = \"weight\", by = \"Country\", na.rm = T, digits = 0)<br>children_data_long &lt;- children_data_wide %&gt;% gather(country, value, -one_of(\"children_betteroff2\", \"weight_name\"), factor_key = T)<br>head(children_data_long)  # look at the top rows of the data<br>sample_n(children_data_long, 10)  # look at a random sample of 10 rows<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"9bde\">The global attitudes team often displays data in&nbsp;<a href=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/global\/2017\/06\/05\/2-public-divided-on-prospects-for-the-next-generation\/economy_02_011\/\" rel=\"noreferrer noopener\" target=\"_blank\">horizontal<\/a>&nbsp;<a href=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/global\/2017\/06\/05\/2-public-divided-on-prospects-for-the-next-generation\/economy_02_02\/\" rel=\"noreferrer noopener\" target=\"_blank\">bar<\/a>&nbsp;<a href=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/global\/2017\/06\/05\/2-public-divided-on-prospects-for-the-next-generation\/economy_02_031\/\" rel=\"noreferrer noopener\" target=\"_blank\">charts<\/a>. With the R graphics package ggplot2, which loads automatically as part of the tidyverse package, any researcher with data can do this, too.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"1053\">First we will have to manipulate the data in order to make a plot that looks similar to those published in Pew Research Center reports. The opposing bar chart will require both negative and positive values, so we create a new variable called children_bars below that makes any \u201cworse off\u201d category negative while keeping the \u201cbetter off\u201d values positive. We map the bar color to our graphic using `fill = children_betteroff2`. We can use our new children_bars variable to sort the data based on the \u201cbetter off\u201d values. Otherwise, the sorting will not function in the way we want.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"a59e\">To create the dataset we need for the graphic, we filter the children_data_long dataframe to only the \u201cbetter off\u201d or \u201cworse off\u201d responses, pipe it to ggplot2 and customize the design. The fct_reorder function is part of the tidyverse and allows us to sort the data by the percent who say \u201cbetter off\u201d at the country level in descending order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"d8ce\">Below, I also specify the hexadecimal color to fill in the bars, use coord_flip() to make the bars horizontal instead of the default vertical and add labels to denote each category at the top and each bar\u2019s value by country.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># specify top margin<br>margin(t = 10)<br>p &lt;- children_data_long %&gt;%<br>  filter(!(children_betteroff2 %in% c(\"Don\u2019t know (DO NOT READ)\",<br>                                      \"Same (DO NOT READ)\",<br>                                      \"Refused (DO NOT READ)\")<br>  )) %&gt;%<br>  mutate(<br>    children_bars = ifelse(children_betteroff2 == \"Worse off\", value * -1, value),<br>    children_betteroff2 = fct_relevel(children_betteroff2, <br>                                      \"Worse off\", \"Better off\"),<br>    better_only = ifelse(children_betteroff2 == \"Better off\", value, 0)<br>  ) %&gt;% <br>  ggplot(<br>    aes(x = reorder(country, better_only),<br>        y = children_bars,<br>        fill = children_betteroff2,<br>        group = children_betteroff2<br>    )<br>  ) +<br>  geom_bar(stat = \"identity\") +<br>  geom_label(<br>    aes(<br>      label = abs(as.numeric(children_bars))<br>      <br>    ),<br>    fill = \"white\"<br>  ) + <br>  scale_fill_manual(values = c(\"Better off\" = \"#949D48\", \"Worse off\" = \"#006699\")) +<br>  coord_flip() +<br>  theme(<br>    axis.line = element_blank(),<br>    panel.background = element_blank(),<br>    axis.ticks = element_blank(),<br>    legend.position = \"top\", <br>    legend.title = element_blank(),<br>    axis.title = element_blank(),<br>    axis.text.x = element_blank(),<br>    axis.text.y = element_text(size = 11, face = \"bold\")<br>  )plot(p)<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/max\/1400\/1*SrRqQcJ08yeWDvFa1115kw.jpeg\" alt=\"\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"cefd\">Hopefully this example analysis can be a resource for studying international survey data in your own projects. And remember, all the data from this post is available for free&nbsp;<a href=\"https:\/\/alpha.pewresearch.org\/pewresearch-org\/global\/datasets\/\" rel=\"noreferrer noopener\" target=\"_blank\">on our website<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" id=\"6831\">Here is all the necessary code used in the post:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Decoded - pewmethods with Global Attitudes<br># just the code#install.packages(\u201cdevtools\u201d)<br>#install_github(\u201cpewresearch\/pewmethods\u201d)library(pewmethods)<br>library(tidyverse)<br>library(rworldmap)<br>library(ggrepel)gap_rd &lt;- haven::read_sav(\"Pew Research Global Attitudes Spring 2017 Dataset WEB FINAL.sav\")gap2017 &lt;- gap_rd %&gt;%<br>  select(<br>    Country,              # country variable<br>    econ_sit,             # current economic situation in your country <br>    children_betteroff2,  # will children be better off\/worse off than parents<br>    weight                # survey weights - very important!<br>  ) %&gt;%<br>  haven::as_factor()unique(as.character(gap2017$Country))  # 38 countries<br>get_spss_label(gap2017, c(\"econ_sit\", \"children_betteroff2\"))  # gives us exact question wordingecon_data_wide &lt;- get_totals(\"econ_sit\", gap2017, wt = \"weight\", by = \"Country\", na.rm = T, digits = 0)<br>head(econ_data_wide)econ_data_long &lt;- gather(econ_data_wide, country, economy, -one_of(\"econ_sit\", \"weight_name\"), factor_key = T)<br>head(econ_data_long)econ_sit_collapse &lt;- econ_data_long %&gt;% <br>  mutate(econ_eval = case_when(<br>    econ_sit == \"Very good\" ~ \"Good\",<br>    econ_sit == \"Somewhat good\" ~ \"Good\",<br>    econ_sit == \"Somewhat bad\" ~ \"Bad\",<br>    econ_sit == \"Very bad\" ~ \"Bad\",<br>    TRUE ~ \"DK\/Refused\")  # parenthesis closes call to `case_when`<br>  ) %&gt;% # parenthesis before pipe closes call to `mutate`<br>  group_by(country, econ_eval) %&gt;%<br>  summarise(share = sum(economy)) <br>final_econ &lt;- econ_sit_collapse %&gt;% spread(econ_eval, share)head(final_econ&#091;c(\"country\", \"Good\", \"Bad\", \"DK\/Refused\")])final_econ &lt;- final_econ %&gt;%<br>  mutate(econ_good_cat = case_when(<br>    Good &lt; 20 ~ \"&lt;20%\",<br>    Good %in% 20:34 ~ \"20-34\",<br>    Good %in% 35:49 ~ \"35-49\",<br>    Good %in% 50:64 ~ \"50-64\",<br>    Good %in% 65:80 ~ \"65-80\",<br>    Good &gt; 80 ~ \"&gt;80%\") %&gt;%   <br>      fct_relevel(\"&lt;20%\", \"20-34\", \"35-49\", \"50-64\", \"65-80\", \"&gt;80%\")<br>  ) %&gt;% <br>  ungroupsPDF &lt;- joinCountryData2Map(final_econ,<br>                            joinCode = \"NAME\",<br>                            nameJoinColumn = \"country\")mapCountryData(sPDF,<br>               nameColumnToPlot = \"econ_good_cat\",<br>               catMethod = \"categorical\",<br>               colourPalette = c(\"#1F497D\", \"#8DB5E2\", \"#C5D9F1\", \"#C4CA8A\", \"#949D48\", \"#707636\"),<br>               mapTitle = \"% who say the current economic nsituation in our country is good, 2017\",<br>               missingCountryCol = \"#ffffff\")gap2017_EU &lt;- gap2017 %&gt;% <br>  filter(Country %in% c(\"United Kingdom\", \"France\", \"Germany\", \"Netherlands\",<br>                        \"Spain\", \"Sweden\", \"Poland\", \"Greece\", \"Hungary\", \"Italy\"))children_data_wide &lt;- get_totals(\"children_betteroff2\", gap2017_EU, wt = \"weight\", by = \"Country\", na.rm = T, digits = 0)<br>children_data_long &lt;- children_data_wide %&gt;% gather(country, value, -one_of(\"children_betteroff2\", \"weight_name\"), factor_key = T)<br>head(children_data_long)  # look at the top rows of the data<br>sample_n(children_data_long, 10)  # look at a random sample of 10 rows# specify top margin<br>margin(t = 10)<br>p &lt;- children_data_long %&gt;%<br>  filter(!(children_betteroff2 %in% c(\"Don\u2019t know (DO NOT READ)\",<br>                                      \"Same (DO NOT READ)\",<br>                                      \"Refused (DO NOT READ)\")<br>  )) %&gt;%<br>  mutate(<br>    children_bars = ifelse(children_betteroff2 == \"Worse off\", value * -1, value),<br>    children_betteroff2 = fct_relevel(children_betteroff2, <br>                                      \"Worse off\", \"Better off\"),<br>    better_only = ifelse(children_betteroff2 == \"Better off\", value, 0)<br>  ) %&gt;% <br>  ggplot(<br>    aes(x = reorder(country, better_only),<br>        y = children_bars,<br>        fill = children_betteroff2,<br>        group = children_betteroff2<br>    )<br>  ) +<br>  geom_bar(stat = \"identity\") +<br>  geom_label(<br>    aes(<br>      label = abs(as.numeric(children_bars))<br>      <br>    ),<br>    fill = \"white\"<br>  ) + <br>  scale_fill_manual(values = c(\"Better off\" = \"#949D48\", \"Worse off\" = \"#006699\")) +<br>  coord_flip() +<br>  theme(<br>    axis.line = element_blank(),<br>    panel.background = element_blank(),<br>    axis.ticks = element_blank(),<br>    legend.position = \"top\", <br>    legend.title = element_blank(),<br>    axis.title = element_blank(),<br>    axis.text.x = element_blank(),<br>    axis.text.y = element_text(size = 11, face = \"bold\")<br>  )plot(p)<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Data from Pew Research Center\u2019s annual Global Attitudes Survey is publicly available.<\/p>\n","protected":false},"author":377,"featured_media":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"sub_headline":"","sub_title":"","_prc_public_revisions":[],"_ppp_expiration_hours":0,"_ppp_enabled":false,"ai_generated_summary":"","relatedPosts":[],"_prc_fork_parent":0,"_prc_fork_status":"","_prc_active_fork":0,"datacite_doi":"","datacite_doi_citation":"","_prc_seo_qr_attachment_id":0,"spoken_article_player_enabled":true,"displayBylines":true,"footnotes":"","prc_watchers":[]},"categories":[],"bylines":[853],"collection":[],"_post_visibility":[],"decoded-category":[531,537],"formats":[],"_fund_pool":[],"languages":[],"regions-countries":[],"research-teams":[524],"workflow-status":[],"class_list":["post-111505","decoded","type-decoded","status-publish","hentry","bylines-kat-devlin","decoded-category-coding-how-to","decoded-category-international-surveys","research-teams-decoded"],"label":"Decoded","post_parent":0,"word_count":2472,"canonical_url":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/decoded\/2020\/04\/13\/analyzing-international-survey-data-with-the-pewmethods-r-package\/","art_direction":{"A1":{"id":125913,"rawUrl":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png","url":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?w=564&h=317&crop=1","width":564,"height":317,"caption":"","chartArt":false},"A2":{"id":125913,"rawUrl":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png","url":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?w=268&h=151&crop=1","width":268,"height":151,"caption":"","chartArt":false},"A3":{"id":125913,"rawUrl":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png","url":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?w=194&h=110&crop=1","width":194,"height":110,"caption":"","chartArt":false},"A4":{"id":125913,"rawUrl":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png","url":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?w=268&h=151&crop=1","width":268,"height":151,"caption":"","chartArt":false},"XL":{"id":125913,"rawUrl":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png","url":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?w=720&h=405&crop=1","width":720,"height":405,"caption":"","chartArt":false},"social":{"id":125913,"rawUrl":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png","url":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-content\/uploads\/sites\/20\/2022\/08\/2020.04.13_decoded_featured.png?w=1200&h=628&crop=1","width":1200,"height":628,"caption":"","chartArt":false}},"_embeds":[],"watchers":[],"table_of_contents":[],"datacite_doi":"","prc_seo_data":{"title":"Analyzing international survey data with the pewmethods R package","description":"Data from Pew Research Center\u2019s annual Global Attitudes Survey is publicly available.","og_title":"Analyzing international survey data with the pewmethods R package","og_description":"Data from Pew Research Center\u2019s annual Global Attitudes Survey is publicly available.","schema_type":"Article","noindex":false,"canonical_url":"","primary_terms":{"category":48},"custom_schema":[],"og_image":125913,"indexnow_submitted_at":null,"gsc_index_status":null},"prepublish_checks":{},"jetpack_sharing_enabled":true,"relatedPostsOrdered":[],"bylinesOrdered":[{"key":"_4h1daajh6","termId":853}],"acknowledgementsOrdered":[],"_links":{"self":[{"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/decoded\/111505","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/decoded"}],"about":[{"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/types\/decoded"}],"author":[{"embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/users\/377"}],"replies":[{"embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/comments?post=111505"}],"version-history":[{"count":2,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/decoded\/111505\/revisions"}],"predecessor-version":[{"id":138522,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/decoded\/111505\/revisions\/138522"}],"wp:attachment":[{"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/media?parent=111505"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/categories?post=111505"},{"taxonomy":"bylines","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/bylines?post=111505"},{"taxonomy":"collection","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/collection?post=111505"},{"taxonomy":"_post_visibility","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/_post_visibility?post=111505"},{"taxonomy":"decoded-category","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/decoded-category?post=111505"},{"taxonomy":"formats","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/formats?post=111505"},{"taxonomy":"_fund_pool","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/_fund_pool?post=111505"},{"taxonomy":"languages","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/languages?post=111505"},{"taxonomy":"regions-countries","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/regions-countries?post=111505"},{"taxonomy":"research-teams","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/research-teams?post=111505"},{"taxonomy":"workflow-status","embeddable":true,"href":"https:\/\/alpha.pewresearch.org\/pewresearch-org\/wp-json\/wp\/v2\/workflow-status?post=111505"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}