[
  {
    "objectID": "index.html",
    "href": "index.html",
    "title": "Hacking Religion: TRS & Data Science in Action",
    "section": "",
    "text": "Introduction: Hacking Religion"
  },
  {
    "objectID": "index.html#why-this-book",
    "href": "index.html#why-this-book",
    "title": "Hacking Religion: TRS & Data Science in Action",
    "section": "Why this book?",
    "text": "Why this book?\nData science is quickly consolidating as a new field, with new tools and user communities emerging seemingly every week! At the same time the field of academic research has opened up into new interdisciplinary vistas, with experts crossing over into new fields, transgressing disciplinary boundaries and deploying tools in new and unexpected ways to develop knowledge. There are many gaps yet to be filled, but one which I found to be particularly glaring is the lack of applied data science documentation around the subject of religion. On one hand, scholars who are working with cutting edge theory seldom pick up the emerging tools of data science. On the other hand, data scientists rarely go beyond dabbling in religious themes. This book aims to bring these two things together: introducing the tools of data science in an applied way, whilst introducing some of the complexities and cutting edge theories which help us to conceptualise and frame our understanding of this knowledge."
  },
  {
    "objectID": "index.html#the-hacker-way",
    "href": "index.html#the-hacker-way",
    "title": "Hacking Religion: TRS & Data Science in Action",
    "section": "The hacker way",
    "text": "The hacker way\nIt’s worth emphasising at the outset that this isn’t meant to be a generic data science book. My own training as a researcher lies in the field of religious ethics, and my engagement with digital technology has, from the very start, been a context for exploring matters of personal values, and social action. A fair bit of ink has been spilled in books, magazines, blogs, zines, and tweets unpacking what exactly it means to be a “hacker”. Pressing beyond some of the more superficial cultural stereotypes, I want to explain a bit here about how hacking can be a much more substantial vision for ethical engagement with technology and social transformation.\nBack in the 1980s Steven Levy tried to capture some of this in his book “Hackers: Heroes of the Computer Revolution”. As Levy put it, the “hacker ethic” included: (1) sharing, (2) openness, (3) decentralisation, (4) free access to computers and (5) world improvement. The key point here is that hacking isn’t just about writing and breaking code, or testing and finding weaknesses in computer systems and networks. It can be a more substantial ethical code.\nThis emphasis on ethics is especially important when we’re doing data science because this kind of research work will put you in positions of influence and grant you power over others. You might think this seems a bit overstated, but it never ceases to amaze me how much bringing a bar chart which succinctly shows some sort of social trend can sway a conversation or decision making process. There is something unusually persuasive that comes with the combination of aesthetics, data and storytelling. I’ve met many people who have come to data science out of a desire to bring about social transformation in some sphere of life. People want to use technology and communication to make the world better. However, it’s possible that this can quickly get out of hand. It’s important to have a clear sense of what sorts of convictions guide your work in this field, a “hacker code” of sorts. With this in mind, I’d like to share with you my own set of principles:\nIt never ceases to amaze me how often people think that, when they’re working for something they think is important it is acceptable to conceal bad news or amplify good or compelling information beyond its real scope. There are always consequences, eventually. When people realise you’ve been misleading or manipulating them your platform and credibility will evaporate. Good work mixed with bad will all get tossed out. And sometimes, our convictions can lead us beyond our true apprehension of a situation.\nPresenting through “facts” an argument can become unnaturally compelling. Wrapping those facts up in something that uses colour, line and shape in a way that is aesthetically pleasing, even beautiful, enhances this allure even further. As you take up the hacker way, it’s vitally important that you always strive to tell the truth. This includes a willingness to acknowledge the limits of your information, and to share the whole set of information. The easiest way to do this is to work with visualation in a responsible way (I’ll get into this a bit more in Chapter 1) and to open up your data and code to scrutiny. By allowing others to try, criticise, edit, and reappropriate your code and data in their own ways, you contribute to knowledge help to build up a community of accountability. The upside of this is that it’s also a lot more fun and interesting to work alongside others.\nFar too often, scholarly research (and theology) has been criticised for being disconnected from reality, making abstract pie-in-the-sky claims about how life should be lived. When exposed to the uncomfortable pressures of reality, these claims can crumble, or even turn sinister. One of the upsides of working with empirical research is that you have a chance to engage with the real world. For this reason, I love to do ethics in a way that arises - bottom-up - from real world experiences and relationships. There’s also the potential that when we make choices based on reliable information drawn from everyday reality like this our policy and culture can be more resilient and accountable. This also works well with the hacker ethos of “learning by doing” and it’s this approach that guides my approach in this book. This isn’t just a book about data analysis, I’m proposing an approach which might be thought of as research-as-code, where you write out instructions to execute the various steps of work. The upside of this is that other researchers can learn from your work, correct and build on it as part of the commons. It takes a bit more time to learn and set things up, but the upside is that you’ll gain access to a set of tools and a research philosophy which is much more powerful.\nHere’s a quick summary of these principles, which I’ll return to periodically as we work through the coding and data in this book:\n\nTell the truth: Be candid about your limits, use visualisation responsibly\nWork transparently: Open data, open code\nWork in community, draw others in by producing reproducible research\nWork with reality, learn by doing"
  },
  {
    "objectID": "index.html#learning-to-code-my-way",
    "href": "index.html#learning-to-code-my-way",
    "title": "Hacking Religion: TRS & Data Science in Action",
    "section": "Learning to code: my way",
    "text": "Learning to code: my way\nThis guide is a little different from other textbooks targetting learning to code. I remember when I was first starting out, I went through a fair few guides, and they all tended to spend about 200 pages on various theoretical bits, how you form an integer, or data structures, subroutines, the logical structure of algorithms or whatever. It was usuallyweeks of reading before I got to actually do anything. I know some people may prefer this approach, but I prefer a problem-focussed approach to learning. Give me something that is broken, or a problem to solve, which engages the things I want to figure out and the motivation for learning just comes much more naturally. And we know from research in cognitive science that these kinds of problem-focussed approaches can tend to faciliate faster learning and better retention, so it’s not just my personal preference, but also justified! It will be helpful for you to be aware of this approach when you get into the book as it explains some of the editorial choices I’ve made and the way I’ve structured things. Each chapter focusses on a problem which is particularly salient for the use of data science to conduct research into religion. That problem will be my focal point, guiding choices of specific aspects of programming to introduce to you as we work our way around that data set and some of the crucial questions that arise in terms of how we handle it. If you find this approach unsatisfying, luckily there are a number of really terrific guides which lay things out slowly and methodically and I will explicitly signpost some of these along the way so that you can do a “deep dive” when you feel like it. Otherwise, I’ll take an accelerated approach to this introduction to data science in R. I expect that you will identify adjacent resources and perhaps even come up with your own creative approaches along the way, which incidentally is how real data science tends to work in practice.\nThere are a range of terrific textbooks out there which cover all these elements in greater depth and more slowly. In particular, I’d recommend that many readers will want to check out Hadley Wickham’s “R For Data Science” book. I’ll include marginal notes in this guide pointing to sections of that book, and a few others which unpack the basic mechanics of R in more detail."
  },
  {
    "objectID": "index.html#getting-set-up",
    "href": "index.html#getting-set-up",
    "title": "Hacking Religion: TRS & Data Science in Action",
    "section": "Getting set up",
    "text": "Getting set up\nEvery single tool, programming language and data set we refer to in this book is free and open source. These tools have been produced by professionals and volunteers who are passionate about data science and research and want to share it with the world, and in order to do this (and following the “hacker way”) they’ve made these tools freely available. This also means that you aren’t restricted to a specific proprietary, expensive, or unavailable piece of software to do this work. I’ll make a few opinionated recommendations here based on my own preferences and experience, but it’s really up to your own style and approach. In fact, given that this is an open source textbook, you can even propose additions to this chapter explaining other tools you’ve found that you want to share with others.\nThere are, right now, primarily two languages that statisticians and data scientists use for this kind of programmatic data science: python and R. Each language has its merits and I won’t rehash the debates between various factions. For this book, we’ll be using the R language. This is, in part, because the R user community and libraries tend to scale a bit better for the work that I’m commending in this book. However, it’s entirely possible that one could use python for all these exercises, and perhaps in the future we’ll have volume two of this book outlining python approaches to the same operations.\nBearing this in mind, the first step you’ll need to take is to download and install R. You can find instructions and install packages for a wide range of hardware on the The Comprehensive R Archive Network (or “CRAN”): https://cran.rstudio.com. Once you’ve installed R, you’ve got some choices to make about the kind of programming environment you’d like to use. You can just use a plain text editor like textedit to write your code and then execute your programs using the R software you’ve just installed. However, most users, myself included, tend to use an integrated development environment (or “IDE”). This is usually another software package with a guided user interface and some visual elements that make it faster to write and test your code. Some IDE packages, will have built-in reference tools so you can look up options for libraries you use in your code, they will allow you to visualise the results of your code execution, and perhaps most important of all, will enable you to execute your programs line by line so you can spot errors more quickly (we call this “debugging”). The two most popular IDE platforms for R coding at the time of writing this textbook are RStudio and Visual Studio. You should download and try out both and stick with your favourite, as the differences are largely aesthetic. I use a combination of RStudio and an enhanced plain text editor Sublime Text for my coding.\nOnce you have R and your pick of an IDE, you are ready to go! Proceed to the next chapter and we’ll dive right in and get started!"
  },
  {
    "objectID": "chapter_1.html#your-first-project-the-uk-census",
    "href": "chapter_1.html#your-first-project-the-uk-census",
    "title": "1  The 2021 UK Census",
    "section": "1.1 Your first project: the UK Census",
    "text": "1.1 Your first project: the UK Census\nLet’s start by importing some data into R. Because R is what is called an object-oriented programming language, we’ll always take our information and give it a home inside a named object. There are many different kinds of objects, which you can specify, but usually R will assign a type that seems to fit best.\nIf you’d like to explore this all in a bit more depth, you can find a very helpful summary in R for Data Science, chapter 8, “data import”.\nIn the example below, we’re going to read in data from a comma separated value file (“csv”) which has rows of information on separate lines in a text file with each column separated by a comma. This is one of the standard plain text file formats. R has a function you can use to import this efficiently called “read.csv”. Each line of code in R usually starts with the object, and then follows with instructions on what we’re going to put inside it, where that comes from, and how to format it:\n\nsetwd(\"/Users/kidwellj/gits/hacking_religion_textbook/hacking_religion\")\nlibrary(here)  |&gt; suppressPackageStartupMessages()\nlibrary(tidyverse)  |&gt; suppressPackageStartupMessages()\nhere::i_am(\"chapter_1.qmd\")\n\nhere() starts at /Users/kidwellj/gits/hacking_religion_textbook/hacking_religion\n\n# Set up local workspace:\nif (dir.exists(\"data\") == FALSE) {\n  dir.create(\"data\") \n}\nif (dir.exists(\"figures\") == FALSE) {\n  dir.create(\"figures\") \n}\nif (dir.exists(\"derivedData\") == FALSE) {\n  dir.create(\"derivedData\")\n}\n\nuk_census_2021_religion &lt;- read.csv(here(\"example_data\", \"census2021-ts030-rgn.csv\"))"
  },
  {
    "objectID": "chapter_1.html#examining-data",
    "href": "chapter_1.html#examining-data",
    "title": "1  The 2021 UK Census",
    "section": "1.2 Examining data:",
    "text": "1.2 Examining data:\nWhat’s in the table? You can take a quick look at either the top of the data frame, or the bottom using one of the following commands:\n\nhead(uk_census_2021_religion)\n\n                 geography   total no_religion christian buddhist  hindu jewish\n1               North East 2647012     1058122   1343948     7026  10924   4389\n2               North West 7417397     2419624   3895779    23028  49749  33285\n3 Yorkshire and The Humber 5480774     2161185   2461519    15803  29243   9355\n4            East Midlands 4880054     1950354   2214151    14521 120345   4313\n5            West Midlands 5950756     1955003   2770559    18804  88116   4394\n6                     East 6335072     2544509   2955071    26814  86631  42012\n  muslim   sikh other no_response\n1  72102   7206  9950      133345\n2 563105  11862 28103      392862\n3 442533  24034 23618      313484\n4 210766  53950 24813      286841\n5 569963 172398 31805      339714\n6 234744  24284 36380      384627\n\n\nThis is actually a fairly ugly table, so I’ll use an R tool called kable to give you prettier tables in the future, like this:\n\nknitr::kable(head(uk_census_2021_religion))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngeography\ntotal\nno_religion\nchristian\nbuddhist\nhindu\njewish\nmuslim\nsikh\nother\nno_response\n\n\n\n\nNorth East\n2647012\n1058122\n1343948\n7026\n10924\n4389\n72102\n7206\n9950\n133345\n\n\nNorth West\n7417397\n2419624\n3895779\n23028\n49749\n33285\n563105\n11862\n28103\n392862\n\n\nYorkshire and The Humber\n5480774\n2161185\n2461519\n15803\n29243\n9355\n442533\n24034\n23618\n313484\n\n\nEast Midlands\n4880054\n1950354\n2214151\n14521\n120345\n4313\n210766\n53950\n24813\n286841\n\n\nWest Midlands\n5950756\n1955003\n2770559\n18804\n88116\n4394\n569963\n172398\n31805\n339714\n\n\nEast\n6335072\n2544509\n2955071\n26814\n86631\n42012\n234744\n24284\n36380\n384627\n\n\n\n\n\nYou can see how I’ve nested the previous command inside the kable command. For reference, in some cases when you’re working with really complex scripts with many different libraries and functions, they may end up with functions that have the same name. You can specify the library where the function is meant to come from by preceding it with :: as we’ve done knitr:: above. The same kind of output can be gotten using tail:\n\nknitr::kable(tail(uk_census_2021_religion))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngeography\ntotal\nno_religion\nchristian\nbuddhist\nhindu\njewish\nmuslim\nsikh\nother\nno_response\n\n\n\n\n5\nWest Midlands\n5950756\n1955003\n2770559\n18804\n88116\n4394\n569963\n172398\n31805\n339714\n\n\n6\nEast\n6335072\n2544509\n2955071\n26814\n86631\n42012\n234744\n24284\n36380\n384627\n\n\n7\nLondon\n8799728\n2380404\n3577681\n77425\n453034\n145466\n1318754\n144543\n86759\n615662\n\n\n8\nSouth East\n9278068\n3733094\n4313319\n54433\n154748\n18682\n309067\n74348\n54098\n566279\n\n\n9\nSouth West\n5701186\n2513369\n2635872\n24579\n27746\n7387\n80152\n7465\n36884\n367732\n\n\n10\nWales\n3107494\n1446398\n1354773\n10075\n12242\n2044\n66947\n4048\n15926\n195041"
  },
  {
    "objectID": "chapter_1.html#parsing-and-exploring-your-data",
    "href": "chapter_1.html#parsing-and-exploring-your-data",
    "title": "1  The 2021 UK Census",
    "section": "1.3 Parsing and Exploring your data",
    "text": "1.3 Parsing and Exploring your data\nThe first thing you’re going to want to do is to take a smaller subset of a large data set, either by filtering out certain columns or rows. Now let’s say we want to just work with the data from the West Midlands, and we’d like to omit some of the columns. We can choose a specific range of columns using select, like this:\nYou can use the filter command to do this. To give an example, filter can pick a single row in the following way:\n\nuk_census_2021_religion_wmids &lt;- uk_census_2021_religion %&gt;% filter(geography==\"West Midlands\")  \n\nNow we’ll use select in a different way to narrow our data to specific columns that are needed (no totals!).\nSome readers will want to pause here and check out Hadley Wickham’s “R For Data Science” book, in the section, “Data visualisation” to get a fuller explanation of how to explore your data.\nIn keeping with my goal to demonstrate data science through examples, we’re going to move on to producing some snappy looking charts for this data."
  },
  {
    "objectID": "chapter_1.html#making-your-first-data-visulation-the-humble-bar-chart",
    "href": "chapter_1.html#making-your-first-data-visulation-the-humble-bar-chart",
    "title": "1  The 2021 UK Census",
    "section": "1.4 Making your first data visulation: the humble bar chart",
    "text": "1.4 Making your first data visulation: the humble bar chart\nWe’ve got a nice lean set of data, so now it’s time to visualise this. We’ll start by making a pie chart:\n\nuk_census_2021_religion_wmids &lt;- uk_census_2021_religion_wmids %&gt;% select(no_religion:no_response)\nuk_census_2021_religion_wmids &lt;- gather(uk_census_2021_religion_wmids)\n\nThere are two basic ways to do visualisations in R. You can work with basic functions in R, often called “base R” or you can work with an alternative library called ggplot:\n\n1.4.1 Base R\n\ndf &lt;- uk_census_2021_religion_wmids[order(uk_census_2021_religion_wmids$value,decreasing = TRUE),]\nbarplot(height=df$value, names=df$key)\n\n\n\n\n\n\n1.4.2 GGPlot\n\nggplot(uk_census_2021_religion_wmids, aes(x = key, y = value)) +\n  geom_bar(stat = \"identity\")\n\n\n2\n\nWe’ll re-order the column by size.\n\n\n\n\n\n\n2ggplot(uk_census_2021_religion_wmids, aes(x= reorder(key,-value),value)) + geom_bar(stat =\"identity\")\n\n\n\n\nLet’s assume we’re working with a data set that doesn’t include a “totals” column and that we might want to get sums for each column. This is pretty easy to do in R:\n\n1uk_census_2021_religion_totals &lt;- uk_census_2021_religion %&gt;% select(no_religion:no_response)\nuk_census_2021_religion_totals &lt;- uk_census_2021_religion_totals %&gt;%\n2   summarise(across(everything(), ~ sum(., na.rm = TRUE)))\n3uk_census_2021_religion_totals &lt;- gather(uk_census_2021_religion_totals)\n4ggplot(uk_census_2021_religion_totals, aes(x= reorder(key,-value),value)) + geom_bar(stat =\"identity\")\n\n\n1\n\nFirst, remove the column with region names and the totals for the regions as we want just integer data.\n\n2\n\nSecond calculate the totals. In this example we use the tidyverse library dplyr(), but you can also do this using base R with colsums() like this: uk_census_2021_religion_totals &lt;- colSums(uk_census_2021_religion_totals, na.rm = TRUE). The downside with base R is that you’ll also need to convert the result into a dataframe for ggplot like this: uk_census_2021_religion_totals &lt;- as.data.frame(uk_census_2021_religion_totals)\n\n3\n\nIn order to visualise this data using ggplot, we need to shift this data from wide to long format. This is a quick job using gather()\n\n4\n\nNow plot it out and have a look!\n\n\n\n\n\n\n\nYou might have noticed that these two dataframes give us somewhat different results. But with data science, it’s much more interesting to compare these two side-by-side in a visualisation. We can join these two dataframes and plot the bars side by side using bind() - which can be done by columns with cbind() and rows using rbind():\n\nuk_census_2021_religion_merged &lt;- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)\n\nDo you notice there’s going to be a problem here? How can we tell one set from the other? We need to add in something idenfiable first! This isn’t too hard to do as we can simply create a new column for each with identifiable information before we bind them:\n\nuk_census_2021_religion_totals$dataset &lt;- c(\"totals\")\nuk_census_2021_religion_wmids$dataset &lt;- c(\"wmids\")\nuk_census_2021_religion_merged &lt;- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)\n\nNow we’re ready to plot out our data as a grouped barplot:\n\nggplot(uk_census_2021_religion_merged, aes(fill=dataset, x= reorder(key,-value), value)) + geom_bar(position=\"dodge\", stat =\"identity\")\n\n\n\n\nIf you’re looking closely, you will notice that I’ve added two elements to our previous ggplot. I’ve asked ggplot to fill in the columns with reference to the dataset column we’ve just created. Then I’ve also asked ggplot to alter the position=\"dodge\" which places bars side by side rather than stacked on top of one another. You can give it a try without this instruction to see how this works. We will use stacked bars in a later chapter, so remember this feature.\nIf you inspect our chart, you can see that we’re getting closer, but it’s not really that helpful to compare the totals. What we need to do is get percentages that can be compared side by side. This is easy to do using another dplyr feature mutate:\nIt’s worth noting that an alternative approach is to leave the numbers intact and simply label them differently so they render as percentages on your charts. You can do this with the `scales() library and the label_percent() function. The downside of this approach is that it won’t transfer to tables if you make them.\n\nuk_census_2021_religion_totals &lt;- uk_census_2021_religion_totals %&gt;% \n  dplyr::mutate(perc = scales::percent(value / sum(value), accuracy = 0.1, trim = FALSE))\nuk_census_2021_religion_wmids &lt;- uk_census_2021_religion_wmids %&gt;% \n  dplyr::mutate(perc = scales::percent(value / sum(value), accuracy = 0.1, trim = FALSE))\nuk_census_2021_religion_merged &lt;- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)\nggplot(uk_census_2021_religion_merged, aes(fill=dataset, x=key, y=perc)) + geom_bar(position=\"dodge\", stat =\"identity\")\n\n\n\n\nNow you can see a very rough comparison, which sets bars from the W Midlands data and overall data side by side for each category. The same principles that we’ve used here can be applied to draw in more data. You could, for example, compare census data from different years, e.g. 2001 2011 and 2021. Our use of dplyr::mutate above can be repeated to add an infinite number of further series’ which can be plotted in bar groups.\nWe’ll draw this data into comparison with later sets in the next chapter. But the one glaring issue which remains for our chart is that it’s lacking in really any aesthetic refinements. This is where ggplot really shines as a tool as you can add all sorts of things.\nThese are basically just added to our ggplot code. So, for example, let’s say we want to improve the colours used for our bars. You can specify the formatting for the fill on the scale using scale_fill_brewer. This uses a particular tool (and a personal favourite of mine) called colorbrewer. Part of my appreciation of this tool is that you can pick colours which are not just visually pleasing, and produce useful contrast / complementary schemes, but you can also work proactively to accommodate colourblindness. Working with colour schemes which can be divergent in a visually obvious way will be even more important when we work on geospatial data and maps in a later chapter.\n\nggplot(uk_census_2021_religion_merged, aes(fill=dataset, x=key, y=perc)) + geom_bar(position=\"dodge\", stat =\"identity\") + scale_fill_brewer(palette = \"Set1\")\n\n\n\n\nWe might also want to add a border to our bars to make them more visually striking (notice the addition of color to the geom_bar below. I’ve also added reorder() to the x value to sort descending from the largest to smallest.\nYou can find more information about reordering ggplots on the R Graph gallery.\n\nuk_census_2021_religion_merged$dataset &lt;- factor(uk_census_2021_religion_merged$dataset, levels = c('wmids', 'totals'))\nggplot(uk_census_2021_religion_merged, aes(fill=fct_reorder(dataset, value), x=reorder(key,-value),value, y=perc)) + geom_bar(position=\"dodge\", stat =\"identity\", colour = \"black\") + scale_fill_brewer(palette = \"Set1\")\n\n\n\n\nWe can fine tune a few other visual features here as well, like adding a title with ggtitle and a them with some prettier fonts with theme_ipsum() (which requires the hrbrthemes() library). We can also remove the x and y axis labels (not the data labels, which are rather important).\n\nggplot(uk_census_2021_religion_merged, aes(fill=fct_reorder(dataset, value), x=reorder(key,-value),value, y=perc)) + geom_bar(position=\"dodge\", stat =\"identity\", colour = \"black\") + scale_fill_brewer(palette = \"Set1\") + ggtitle(\"Religious Affiliation in the UK: 2021\") + xlab(\"\") + ylab(\"\")"
  },
  {
    "objectID": "chapter_1.html#is-your-chart-accurate-telling-the-truth-in-data-science",
    "href": "chapter_1.html#is-your-chart-accurate-telling-the-truth-in-data-science",
    "title": "1  The 2021 UK Census",
    "section": "1.5 Is your chart accurate? Telling the truth in data science",
    "text": "1.5 Is your chart accurate? Telling the truth in data science\nThere is some technical work yet to be done fine-tuning the visualisation of our chart here. But I’d like to pause for a moment and consider an ethical question. Is the title of this chart truthful and accurate? On one hand, it is a straight-forward reference to the nature of the question asked on the 2021 census survey instrument. However, as you will see in the next chapter, large data sets from the same year which asked a fairly similar question yield different results. Part of this could be attributed to the amount of non-respose to this specific question which, in the 2021 census is between 5-6% across many demographics. It’s possible (though perhaps unlikely) that all those non-responses were Sikh respondents who felt uncomfortable identifying themselves on such a survey. If even half of the non-responses were of this nature, this would dramatically shift the results especially in comparison to other minority groups. So there is some work for us to do here in representing non-response as a category on the census.\nIt’s equally possible that someone might feel uncertain when answering, but nonetheless land on a particular decision marking “Christian” when they wondered if they should instead tick “no religion. Some surveys attempt to capture uncertainty in this way, asking respondents to mark how confident they are about their answers, but the census hasn’t capture this so we simply don’t know. If a large portion of respondents in the”Christian” category were hovering between this and another response, again, they might shift their answers when responding on a different day, perhaps having just had a conversation with a friend which shifted their thinking. Even the inertia of survey design can have an effect on this, so responding to other questions in a particular way, thinking about ethnic identity, for example, can prime a person to think about their religious identity in a different or more focussed way, altering their response to the question. For this reason, some survey instruments randomise the order of questions. This hasn’t been done on the census (which would have been quite hard work given that most of the instruments were printed hard copies!), so again, we can’t really be sure if those answers given are stable.\nFinally, researchers have also found that when people are asked to mark their religious affiliation, sometimes they can prefer to mark more than one answer. A person might consider themselves to be “Muslim” but also “Spiritual but not religious” preferring the combination of those identities. It is also the case that respondents can identify with more unexpected hybrid religious identities, such as “Christian” and “Hindu”. The census only allows respondents to tick a single box for the religion category. It is worth noting that, in contrast, the responses for ethnicity allow for combinations. Given that this is the case, it’s impossible to know which way a person went at the fork in the road as they were forced to choose just one half of this kind of hybrid identity. Finally, it is interesting to wonder exactly what it means for a person when they tick a box like this. Is it because they attend synagogue on a weekly basis? Some persons would consider weekly attendance at workship a prerequisite for membership in a group, but others would not. Indeed we can infer from surveys and research which aims to track rates of participation in weekly worship that many people who tick boxes for particular religious identities on the census have never attended a worship service at all.\nWhat does this mean for our results? Are they completely unreliable and invalid? I don’t think this is the case or that taking a clear-eyed look at the force and stability of our underlying data should be cause for despair. Instead, the most appropriate response is humility. Someone has made a statement which is recorded in the census, of this we can be sure. They felt it to be an accurate response on some level based on the information they had at the time. And with regard to the census, it is a massive, almost completely population level, sample so there is additional validity there. The easiest way to represent all this reality in the form of speaking truthfully about our data is to acknowledge that however valid it may seem, it is nonetheless a snapshot. For this reason, I would always advise that the best title for a chart is one which specifies the data set. We should also probably do something different with those non-responses:\n\nggplot(uk_census_2021_religion_merged, aes(fill=fct_reorder(dataset, value), x=reorder(key,-value),value, y=perc)) + geom_bar(position=\"dodge\", stat =\"identity\", colour = \"black\") + scale_fill_brewer(palette = \"Set1\") + ggtitle(\"Religious Affiliation in the 2021 Census of England and Wales\") + xlab(\"\") + ylab(\"\")\n\n\n\n\nChange orientation of X axis labels + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))\nRelabel fields Simplify y-axis labels Add percentage text to bars (or maybe save for next chapter?)"
  },
  {
    "objectID": "chapter_1.html#making-our-script-reproducible",
    "href": "chapter_1.html#making-our-script-reproducible",
    "title": "1  The 2021 UK Census",
    "section": "1.6 Making our script reproducible",
    "text": "1.6 Making our script reproducible\nLet’s take a moment to review our hacker code. I’ve just spent some time addressing how we can be truthful in our data science work. We haven’t done much yet to talk abour reproducibility."
  },
  {
    "objectID": "chapter_1.html#multifactor-visualisation",
    "href": "chapter_1.html#multifactor-visualisation",
    "title": "1  The 2021 UK Census",
    "section": "1.7 Multifactor Visualisation",
    "text": "1.7 Multifactor Visualisation\nOne element of R data analysis that can get really interesting is working with multiple variables. Above we’ve looked at the breakdown of religious affiliation across the whole of England and Wales (Scotland operates an independent census), and by placing this data alongside a specific region, we’ve already made a basic entry into working with multiple variables but this can get much more interesting. Adding an additional quantative variable (also known as bivariate data) into the mix, however can also generate a lot more information and we have to think about visualising it in different ways which can still communicate with visual clarity in spite of the additional visual noise which is inevitable with enhanced complexity. Let’s have a look at the way that religion in England and Wales breaks down by ethnicity.\n\n\n\n\n\n\nWhat is Nomis?\n\n\n\nFor the UK, census data is made available for programmatic research like this via an organisation called NOMIS. Luckily for us, there is an R library you can use to access nomis directly which greatly simplifies the process of pulling data down from the platform. It’s worth noting that if you’re not in the UK, there are similar options for other countries. Nearly every R textbook I’ve ever seen works with USA census data, so you’ll find plenty of documentation available on the tools you can use for US Census data. Similarly for the EU, Canada, Austrailia etc.\nIf you want to draw some data from the nomis platform yourself in R, have a look at the companion cookbook repository.\n\n\n\n# Get table of Census 2011 religion data from nomis\nz &lt;- readRDS(file = (here(\"example_data\", \"z.rds\")))\n\n# Filter down to simplified dataset with England / Wales and percentages without totals\nuk_census_2011_religion &lt;- filter(z, GEOGRAPHY_NAME==\"England and Wales\" & RURAL_URBAN_NAME==\"Total\" & C_RELPUK11_NAME != \"All categories: Religion\")\n# Drop unnecessary columns\nuk_census_2011_religion &lt;- select(uk_census_2011_religion, C_RELPUK11_NAME, OBS_VALUE)\n# Plot results\nplot1 &lt;- ggplot(uk_census_2011_religion, aes(x = C_RELPUK11_NAME, y = OBS_VALUE)) + geom_bar(stat = \"identity\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))\n# ggsave(filename = \"plot.png\", plot = plot1)\n\n# grab daata from nomis for 2001 census religion / ethnicity\nz0 &lt;- readRDS(file = (here(\"example_data\", \"z0.rds\")))\n\n# select relevant columns\nuk_census_2001_religion_ethnicity &lt;- select(z0, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHHUK11_NAME, OBS_VALUE)\n# Filter down to simplified dataset with England / Wales and percentages without totals\nuk_census_2001_religion_ethnicity &lt;- filter(uk_census_2001_religion_ethnicity, GEOGRAPHY_NAME==\"England and Wales\" & C_RELPUK11_NAME != \"All categories: Religion\")\n# Simplify data to only include general totals and omit subcategories\nuk_census_2001_religion_ethnicity &lt;- uk_census_2001_religion_ethnicity %&gt;% filter(grepl('Total', C_ETHHUK11_NAME))\n\n# grab data from nomis for 2011 census religion / ethnicity table\nz1 &lt;- readRDS(file = (here(\"example_data\", \"z1.rds\")))\n\n# select relevant columns\nuk_census_2011_religion_ethnicity &lt;- select(z1, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHPUK11_NAME, OBS_VALUE)\n# Filter down to simplified dataset with England / Wales and percentages without totals\nuk_census_2011_religion_ethnicity &lt;- filter(uk_census_2011_religion_ethnicity, GEOGRAPHY_NAME==\"England and Wales\" & C_RELPUK11_NAME != \"All categories: Religion\" & C_ETHPUK11_NAME != \"All categories: Ethnic group\")\n# Simplify data to only include general totals and omit subcategories\nuk_census_2011_religion_ethnicity &lt;- uk_census_2011_religion_ethnicity %&gt;% filter(grepl('Total', C_ETHPUK11_NAME))\n\n# grab data from nomis for 2021 census religion / ethnicity table\nz2 &lt;- readRDS(file = (here(\"example_data\", \"z2.rds\")))\n\n# select relevant columns\nuk_census_2021_religion_ethnicity &lt;- select(z2, GEOGRAPHY_NAME, C2021_RELIGION_10_NAME, C2021_ETH_8_NAME, OBS_VALUE)\n# Filter down to simplified dataset with England / Wales and percentages without totals\nuk_census_2021_religion_ethnicity &lt;- filter(uk_census_2021_religion_ethnicity, GEOGRAPHY_NAME==\"England and Wales\" & C2021_RELIGION_10_NAME != \"Total\" & C2021_ETH_8_NAME != \"Total\")\n# 2021 census includes white sub-groups so we need to omit those so we just have totals:\nuk_census_2021_religion_ethnicity &lt;- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != \"White: English, Welsh, Scottish, Northern Irish or British\" & C2021_ETH_8_NAME != \"White: Irish\" & C2021_ETH_8_NAME != \"White: Gypsy or Irish Traveller, Roma or Other White\")\n\nggplot(uk_census_2011_religion_ethnicity, aes(fill=C_ETHPUK11_NAME, x=C_RELPUK11_NAME, y=OBS_VALUE)) + geom_bar(position=\"dodge\", stat =\"identity\", colour = \"black\") + scale_fill_brewer(palette = \"Set1\") + ggtitle(\"Religious Affiliation in the 2021 Census of England and Wales\") + xlab(\"\") + ylab(\"\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))\n\n\n\n\nThe trouble with using grouped bars here, as you can see, is that there are quite sharp disparities which make it hard to compare in meaningful ways. We could use logarithmic rather than linear scaling as an option, but this is hard for many general public audiences to apprecaite without guidance. One alternative quick fix is to extract data from “white” respondents which can then be placed in a separate chart with a different scale.\n\n# Filter down to simplified dataset with England / Wales and percentages without totals\nuk_census_2011_religion_ethnicity_white &lt;- filter(uk_census_2011_religion_ethnicity, C_ETHPUK11_NAME == \"White: Total\")\nuk_census_2011_religion_ethnicity_nonwhite &lt;- filter(uk_census_2011_religion_ethnicity, C_ETHPUK11_NAME != \"White: Total\")\n\nggplot(uk_census_2011_religion_ethnicity_nonwhite, aes(fill=C_ETHPUK11_NAME, x=C_RELPUK11_NAME, y=OBS_VALUE)) + geom_bar(position=\"dodge\", stat =\"identity\", colour = \"black\") + scale_fill_brewer(palette = \"Set1\") + ggtitle(\"Religious Affiliation in the 2021 Census of England and Wales\") + xlab(\"\") + ylab(\"\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))\n\n\n\n\nThis still doesn’t quite render with as much visual clarity and communication as I’d like. For a better look, we can use a technique in R called “faceting” to create a series of small charts which can be viewed alongside one another.\n\nggplot(uk_census_2011_religion_ethnicity_nonwhite, aes(x=C_RELPUK11_NAME, y=OBS_VALUE)) + geom_bar(position=\"dodge\", stat =\"identity\", colour = \"black\") + facet_wrap(~C_ETHPUK11_NAME, ncol = 2) + scale_fill_brewer(palette = \"Set1\") + ggtitle(\"Religious Affiliation in the 2011 Census of England and Wales\") + xlab(\"\") + ylab(\"\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))\n\n\n\n\nFor our finale chart, I’d like to take the faceted chart we’ve just done, and add in totals for the previous two census years (2001 and 2011) so we can see how trends are changing in terms of religious affiliation within ethnic self-identification categories. We’ll draw on some techniques we’re already developed above using rbind() to connect up each of these charts (after we’ve added a column identifying each chart by the census year). We will also need to use one new technique to change the wording of ethnic categories as this isn’t consistent from one census to the next and ggplot will struggle to chart things if the terms being used are exactly the same. We’ll use mutate() again to accomplish this with some slightly different code.\n\n# First add column to each dataframe so we don't lose track of the census it comes from:\nuk_census_2001_religion_ethnicity$dataset &lt;- c(\"2001\")\nuk_census_2011_religion_ethnicity$dataset &lt;- c(\"2011\")\nuk_census_2021_religion_ethnicity$dataset &lt;- c(\"2021\")\n\n# Let's tidy the names of each column:\n\nnames(uk_census_2001_religion_ethnicity) &lt;- c(\"Geography\", \"Religion\", \"Ethnicity\", \"Value\", \"Year\")\nnames(uk_census_2011_religion_ethnicity) &lt;- c(\"Geography\", \"Religion\", \"Ethnicity\", \"Value\", \"Year\")\nnames(uk_census_2021_religion_ethnicity) &lt;- c(\"Geography\", \"Religion\", \"Ethnicity\", \"Value\", \"Year\")\n\n# Next we need to change the terms using mutate()\nuk_census_2001_religion_ethnicity &lt;- uk_census_2001_religion_ethnicity %&gt;% \n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^White: Total$\", replacement = \"White\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Mixed: Total$\", replacement = \"Mixed\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Asian: Total$\", replacement = \"Asian\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Black or Black British: Total$\", replacement = \"Black\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Chinese or Other ethnic group: Total$\", replacement = \"Other\"))\n  \nuk_census_2011_religion_ethnicity &lt;- uk_census_2011_religion_ethnicity %&gt;% \n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^White: Total$\", replacement = \"White\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Mixed/multiple ethnic group: Total$\", replacement = \"Mixed\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Asian/Asian British: Total$\", replacement = \"Asian\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Black/African/Caribbean/Black British: Total$\", replacement = \"Black\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Other ethnic group: Total$\", replacement = \"Other\"))\n\nuk_census_2021_religion_ethnicity &lt;- uk_census_2021_religion_ethnicity %&gt;% \n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^White: Total$\", replacement = \"White\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Mixed or Multiple ethnic groups$\", replacement = \"Mixed\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Asian, Asian British or Asian Welsh$\", replacement = \"Asian\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Black, Black British, Black Welsh, Caribbean or African$\", replacement = \"Black\")) %&gt;%\n  mutate(Ethnicity = str_replace_all(Ethnicity, \n            pattern = \"^Other ethnic group$\", replacement = \"Other\"))\n\n# Now let's merge the tables:\n\nuk_census_merged_religion_ethnicity &lt;- rbind(uk_census_2021_religion_ethnicity, uk_census_2011_religion_ethnicity)\n\nuk_census_merged_religion_ethnicity &lt;- rbind(uk_census_merged_religion_ethnicity, uk_census_2001_religion_ethnicity)\n\n# As above, we'll split out non-white and white:\n\nuk_census_merged_religion_ethnicity_nonwhite &lt;- filter(uk_census_merged_religion_ethnicity, Ethnicity != \"White\")\n\n# Time to plot!\n\nggplot(uk_census_merged_religion_ethnicity_nonwhite, aes(fill=Year, x=Religion, y=Value)) + geom_bar(position=\"dodge\", stat =\"identity\", colour = \"black\") + facet_wrap(~Ethnicity, ncol = 2) + scale_fill_brewer(palette = \"Set1\") + ggtitle(\"Religious Affiliation in the 2001-2021 Census of England and Wales\") + xlab(\"\") + ylab(\"\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))\n\n\n\n\nThere are a few formatting issues which remain. Our y-axis number labels are in scientific format which isn’t really very easy to read. You can use the very powerful and flexible scales() library to bring in some more readable formatting of numbers in a variety of places in R including in ggplot visualizations.\n\nlibrary(scales) |&gt; suppressPackageStartupMessages()\nggplot(uk_census_merged_religion_ethnicity_nonwhite, aes(fill=Year, x=Religion, y=Value)) + geom_bar(position=\"dodge\", stat =\"identity\", colour = \"black\") + facet_wrap(~Ethnicity, ncol = 2) + scale_fill_brewer(palette = \"Set1\") + scale_y_continuous(labels = unit_format(unit = \"M\", scale = 1e-6), breaks = breaks_extended(8)) + ggtitle(\"Religious Affiliation in the 2001-2021 Census of England and Wales\") + xlab(\"\") + ylab(\"\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))\n\n\n\n# https://ggplot2-book.org/scales-position#sec-position-continuous-breaks\n\nThis chart shows an increase in almost every category, though it’s a bit hard to read in some cases. However, this information is based on the increase in raw numbers. It’s possbile that numbers may be going up, but in some cases the percentage share for a particular category has actually gone down. Let’s transform and visualise our data as percentages to see what kind of trends we can actually isolate:\n\nuk_census_merged_religion_ethnicity &lt;- uk_census_merged_religion_ethnicity %&gt;%\n  group_by(Ethnicity, Year) %&gt;%\n  dplyr::mutate(Percent = Value/sum(Value))\n\nggplot(uk_census_merged_religion_ethnicity, aes(fill=Year, x=Religion, y=Percent)) + geom_bar(position=\"dodge\", stat =\"identity\", colour = \"black\") + facet_wrap(~Ethnicity, scales=\"free_x\") + scale_fill_brewer(palette = \"Set1\") + scale_y_continuous(labels = scales::percent) + ggtitle(\"Religious Affiliation in the 2001-2021 Census of England and Wales\") + xlab(\"\") + ylab(\"\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))\n\n\n\n\nNow you can see why this shift is important - the visualisation tells a completely different story in some cases across the two different charts. In the first, working off raw numbers we see a net increase in Christianity across all categories. But if we take into account the fact that the overall share of population is growing for each of these groups, their actual composition is changing in a different direction. The proportion of each group is declining across the three census periods (albeit with an exception for the “Other” category from 2011 to 2021).\nTo highlight a few features of this final plot, I’ve used a specific feature within facet_wrap scales = \"free_x\" to let each of the individual facets adjust the total range on the x-axis. Since we’re looking at trends here and not absolute values, having correspondence across scales isn’t important and this makes for something a bit more visually tidy. I’ve also shifted the code for scale_y_continuous to render values as percentages (rather than millions).\nIn case you want to print this plot out and hang it on your wall, you can use the ggsave tool to render the chart as an image file:\n\nplot1 &lt;- ggplot(uk_census_merged_religion_ethnicity, aes(fill=Year, x=Religion, y=Percent)) + geom_bar(position=\"dodge\", stat =\"identity\", colour = \"black\") + facet_wrap(~Ethnicity, scales=\"free_x\") + scale_fill_brewer(palette = \"Set1\") + scale_y_continuous(labels = scales::percent) + ggtitle(\"Religious Affiliation in the 2001-2021 Census of England and Wales\") + xlab(\"\") + ylab(\"\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))\n\nggsave(\"chart.png\", plot=plot1, width = 8, height = 10, units=c(\"in\"))"
  },
  {
    "objectID": "chapter_2.html#loading-in-some-data",
    "href": "chapter_2.html#loading-in-some-data",
    "title": "2  Survey Data: Spotlight Project",
    "section": "2.1 Loading in some data",
    "text": "2.1 Loading in some data\n\n# R Setup -----------------------------------------------------------------\nsetwd(\"/Users/kidwellj/gits/hacking_religion_textbook/hacking_religion\")\nlibrary(here)  |&gt; suppressPackageStartupMessages()\nlibrary(tidyverse)  |&gt; suppressPackageStartupMessages()\n# used for importing SPSS .sav files\nlibrary(haven)   |&gt; suppressPackageStartupMessages()\nhere::i_am(\"chapter_2.qmd\")\n\nhere() starts at /Users/kidwellj/gits/hacking_religion_textbook/hacking_religion\n\nclimate_experience_data &lt;- read_sav(here(\"example_data\", \"climate_experience_data.sav\"))\n\nThe first thing to note here is that we’ve drawn in a different type of data file, this time from an .sav file, usully produced by the statistics software package SPSS. This uses a different R Library (I use haven for this). The upside is that in some cases where you have survey data with both a code and a value like “1” is eqivalent to “very much agree” this will preserve both in the R dataframe that is created. Now that you’ve loaded in data, you have a new R dataframe called “climate_experience_data” with a lot of columns with just under 1000 survey responses."
  },
  {
    "objectID": "chapter_2.html#how-can-you-ask-about-religion",
    "href": "chapter_2.html#how-can-you-ask-about-religion",
    "title": "2  Survey Data: Spotlight Project",
    "section": "2.2 How can you ask about religion?",
    "text": "2.2 How can you ask about religion?\nOne of the challenges we faced when running this study is how to gather responsible data from surveys regarding religious identity. We’ll dive into this in depth as we do analysis and look at some of the agreements and conflicts in terms of respondent attribution. Just to set the stage, we used the following kinds of question to ask about religion and spirituality:\n\n2.2.1 “What is your religion?”\n\nQuestion 56 asks respondents simply, “What is your religion?” and then provides a range of possible answers. We included follow-up questions regarding denomination for respondents who indicated they were “Christian” or “Muslim”. For respondents who ticked “Christian” we asked, “What is your denomination?” nad for respondents who ticked “Muslim” we asked “Which of the following would you identify with?” and then left a range of possible options which could be ticked such as “Sunni,” “Shia,” “Sufi” etc.\n\nThis is one way of measuring religion, that is, to ask a person if they consider themselves formally affiliated with a particular group. This kind of question has some (serious) limitations, but we’ll get to that in a moment.\n\n\n2.2.2 “How religious would you say you are?”\nWe also asked respondents (Q57): “Regardless of whether you belong to a particular religion, how religious would you say you are?” and then provided a slider from 0 (not religious at all) to 10 (very religious).\n\n\n2.2.3 Participation in Worship\nWe included some classic indicators about how often respondents go to worship (Q58): Apart from weddings, funerals and other special occasions, how often do you attend religious services? and (Q59): “Q59 Apart from when you are at religious services, how often do you pray?”\n\nMore than once a week (1)\nOnce a week (2)\nAt least once a month (3)\nOnly on special holy days (4)\nNever (5)\n\nEach of these measures a particular kind of dimension, and it is interesting to note that sometimes there are stronger correlations between how often a person attends worship services (weekly versus once a year) and a particular view, than there is between their affiliation (if they are Christian or Pagan). We’ll do some exploratory work shortly to see how this is the case in our sample.\n\n\n2.2.4 Spirituality\nWe also included a series of questions about spirituality in Q52 and used a slightly overlapping nature relatedness scale Q51.\nYou’ll find that many surveys will only use one of these forms of question and ignore the rest. I think this is a really bad idea as religious belonging, identity, and spirituality are far too complex to work off a single form of response. We can also test out how these different attributions relate to other demographic features, like interest in politics, economic attainment, etc.\n\n\n\n\n\n\nSo Who’s Religious?\n\n\n\nAs I’ve already hinted in the previous chapter, measuring religiosity is complicated. I suspect some readers may be wondering something like, “what’s the right question to ask?” here. Do we get the most accurate representation by asking people to self-report their religious affiliation? Or is it more accurate to ask individuals to report on how religious they are? Is it, perhaps, better to assume that the indirect query about practice, e.g. how frequently one attends services at a place of worship may be the most reliable proxy?\nHighlight challenges of various approaches pointing to literature."
  },
  {
    "objectID": "chapter_2.html#exploring-data-around-religious-affiliation",
    "href": "chapter_2.html#exploring-data-around-religious-affiliation",
    "title": "2  Survey Data: Spotlight Project",
    "section": "2.3 Exploring data around religious affiliation:",
    "text": "2.3 Exploring data around religious affiliation:\nLet’s dive into the data and see how this all works out. We’ll start with the question 56 data, around religious affiliation:\n\nreligious_affiliation &lt;- as_tibble(as_factor(climate_experience_data$Q56))\nnames(religious_affiliation) &lt;- c(\"response\")\nreligious_affiliation &lt;- filter(religious_affiliation, !is.na(response))\n\nThere are few things we need to do here to get the data into initial proper shape. This might be called “cleaning” the data:\n\nBecause we imported this data from an SPSS .sav file format using the R haven() library, we need to start by adapting the data into a format that our visualation engine ggplot can handle (a dataframe).\nNext we’ll rename the columns so these names are a bit more useful.\nWe need to omit non-responses so these don’t mess with the counting (these are NA in R)\n\nIf we pause at this point to view the data, you’ll see it’s basically just a long list of survey responses. What we need is a count of each unique response (or factor). This will take a few more steps:\n\nreligious_affiliation_sums &lt;- religious_affiliation %&gt;%  \n1  dplyr::count(response, sort = TRUE) %&gt;%\n2  dplyr::mutate(response = forcats::fct_rev(forcats::fct_inorder(response)))\nreligious_affiliation_sums &lt;- religious_affiliation_sums %&gt;% \n3  dplyr::mutate(perc = scales::percent(n / sum(n), accuracy = .1, trim = FALSE))\n\n\n1\n\nFirst we generate new a dataframe with sums per category and\n\n2\n\n…sort in descending order\n\n3\n\nThen we add new column with percentages based on the sums you’ve just generated\n\n\n\n\nThat should give us a tidy table of results, which you can see if you view the contents of our new religious_affiliation_sums dataframe:\n\nhead(religious_affiliation_sums)\n\n# A tibble: 6 x 3\n  response                        n perc   \n  &lt;fct&gt;                       &lt;int&gt; &lt;chr&gt;  \n1 Christian                     342 \"33.9%\"\n2 Muslim                        271 \"26.9%\"\n3 No religion                   108 \"10.7%\"\n4 Hindu                          72 \" 7.1%\"\n5 Atheist                        54 \" 5.4%\"\n6 Spiritual but not religious    38 \" 3.8%\"\n\n\n\n# make plot\nggplot(religious_affiliation_sums, aes(x = n, y = response)) +\n  geom_col(colour = \"white\") + \n  ## add percentage labels\n  geom_text(aes(label = perc),\n            ## make labels left-aligned and white\n            hjust = 1, nudge_x = -.5, colour = \"white\", size=3)\n\n\n\n\nI’ve added one feature to our chart that wasn’t in the bar charts in chapter 1, text labels with the actual value on each bar.\nYou may be thinking about the plots we’ve just finished in chapter 1 and wondering how they compare. Let’s use the same facet approach that we’ve just used to render this data in a subsetted way.\n\n# First we need to add in data on ethnic self-identification from our respondents:\ndf &lt;- select(climate_experience_data, Q56, Q0)\nreligious_affiliation_ethnicity &lt;- as_tibble(as_factor(df))\nnames(religious_affiliation_ethnicity) &lt;- c(\"Religion\", \"Ethnicity\")\n\nreligious_affiliation_ethnicity_sums &lt;- religious_affiliation_ethnicity %&gt;%  \n  group_by(Ethnicity) %&gt;%\n  dplyr::count(Religion, sort = TRUE) %&gt;%\n  dplyr::mutate(Religion = forcats::fct_rev(forcats::fct_inorder(Religion)))\n\nplot1 &lt;- ggplot(religious_affiliation_ethnicity_sums, aes(x = n, y = Religion)) +\n  geom_col(colour = \"white\") + facet_wrap(~Ethnicity, scales=\"free_x\")\n\nggsave(\"chart.png\", plot=plot1, width = 8, height = 10, units=c(\"in\"))"
  },
  {
    "objectID": "chapter_2.html#working-with-a-continum-religiosity-and-spirituality",
    "href": "chapter_2.html#working-with-a-continum-religiosity-and-spirituality",
    "title": "2  Survey Data: Spotlight Project",
    "section": "2.4 Working With a Continum: Religiosity and Spirituality",
    "text": "2.4 Working With a Continum: Religiosity and Spirituality\nSo far we’ve just worked with bar plots, but there are a lot of other possible visualisations and types of data which demand them.\nAs I’ve mentioned above, on this survey we also asked respondents to tell us on by rating themselves on a scale of 0-10 with 0 being “not religious at all” and 10 being “very religious” in response to the question, “Regardless of whether you belong to a particular religion, how religious would you say you are?”\nWe’ll recycle some code from our previous import to bring in the Q57 data:\n\nreligiosity &lt;- as_tibble(as_factor(climate_experience_data$Q57_1))\nnames(religiosity) &lt;- c(\"response\")\nreligiosity &lt;- filter(religiosity, !is.na(response))\nreligiosity_sums &lt;- religiosity %&gt;%  \n1  dplyr::count(response) %&gt;%\n  dplyr::mutate(response = forcats::fct_rev(forcats::fct_inorder(response)))\nreligiosity_sums &lt;- religiosity_sums %&gt;% \n  dplyr::mutate(perc = scales::percent(n / sum(n), accuracy = .1, trim = FALSE))\n\n\n1\n\nNote: we have removed sort = TRUE in the above statement as it will enforce sorting the data by quantities rather than the factor order. It wouldn’t really make sense to plot this chart in the order of response.\n\n\n\n\nNow, let’s plot that data:\n\ncaption &lt;- \"Respondent Religiosity\"\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) +\n1  geom_col(colour = \"white\", aes(fill = response)) +\n  ## get rid of all elements except y axis labels + adjust plot margin\n2  coord_flip() +\n  theme(plot.margin = margin(rep(15, 4))) +\n  labs(caption = caption)\n\n\n1\n\nWe’ve added colors, because colours are fun.\n\n2\n\nAlso new here is coord_flip to rotate the chart so we have bars going horizontally\n\n\n\n\n\n\n\nSince we’re thinking about how things look just now, let’s play with themes for a minute. ggplot is a really powerful tool for visualising information, but it also has some quite nice features for making things look pretty.\nIf you’d like to take a proper deep dive on all this theme stuff, R-Charts has a great set of examples showing you how a number of different theme packages look in practice, “R-Charts on Themes”.\nR has a number of built-in themes, but these are mostly driven by functional concerns, such as whether you might want to print your chart or have a less heavy look overall. So for example you might use theme_light() in the following way:\n\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) +\n  geom_col(colour = \"white\", aes(fill = response)) +\n  ## get rid of all elements except y axis labels + adjust plot margin\n  coord_flip() +\n  theme(plot.margin = margin(rep(15, 4))) +\n  labs(caption = caption) +\n  theme_light()\n\n\n\n\nYou can also use additional packages like ggthemes() or hrbrthemes() so for example we might want to try the pander theme which has it’s own special (and very cheerful) colour palette.\n\nlibrary(ggthemes)  |&gt; suppressPackageStartupMessages()\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) + geom_col(colour = \"white\", aes(fill = response)) + coord_flip() + theme(plot.margin = margin(rep(15, 4))) + labs(caption = caption) + \n  theme_pander() +\n  scale_fill_pander()\n\n\n\n\nOr, you might try the well-crafted typgraphy from hbrthemes in the theme_ipsum_pub theme:\n\nlibrary(hrbrthemes)  |&gt; suppressPackageStartupMessages()\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) + geom_col(colour = \"white\", aes(fill = response)) + coord_flip() + theme(plot.margin = margin(rep(15, 4))) + labs(caption = caption) + \n  theme_ipsum_pub() +\n  scale_fill_pander()\n\n\n\n\nWe’re going to come back to this chart, but let’s set it to one side for a moment and build up a visualisation of the spirituality scale data. The spirituality scale questions come from research by ___ and ___. These researchers developed a series of questions which they asked respondents in a survey. The advantage here is that you’re getting at the question of spirituality from a lot of different angles, and then you combine the scores from all the questions to get a mean “spirituality score”.\n\n### Spirituality scale  --------------------------------------------------------------\n# Calculate overall mean spirituality score based on six questions:\nclimate_experience_data$Q52_score &lt;- rowMeans(select(climate_experience_data, Q52a_1:Q52f_1))\n\nLike we did in chapter 1, let’s start by exploring the data and get a bit of a sense of the character of the responses overall. One good place to start is to find out the mean response for our two continum questions:\n\n# t_testing and means\n\n# Spirituality scale\n\n# JK note to self: need to fix stat_summary plot here\n\n# stat_summary(climate_experience_data$Q52_score)\nmean(climate_experience_data$Q52_score)\n\n[1] 6.047454\n\n# Q57 Regardless of whether you belong to a particular religion, how religious would you say you are?\n# 0-10, Not religious at all =&gt; Very religious; mean=5.58\n\nmean(climate_experience_data$Q57_1) # religiosity\n\n[1] 5.581349\n\n# Q58 Apart from weddings, funerals and other special occasions, how often do you attend religious services?\n# coded at 1-5, lower value = stronger mean=3.439484\n\nmean(climate_experience_data$Q58) # service attendance\n\n[1] 3.439484\n\n# Q59 Apart from when you are at religious services, how often do you pray?\n# coded at 1-5, lower = stronger mean=2.50496\n\nmean(climate_experience_data$Q59)\n\n[1] 2.50496\n\n\nNow let’s try out some visualisations:\n\n## Q52 Spirituality data ------------------------\n\nq52_data &lt;- select(climate_experience_data, Q52a_1:Q52f_1)\n# Data is at wide format, we need to make it 'tidy' or 'long'\nq52_data &lt;- q52_data %&gt;% \n  gather(key=\"text\", value=\"value\") %&gt;%\n  # rename columns\n  mutate(text = gsub(\"Q52_\", \"\",text, ignore.case = TRUE)) %&gt;%\n  mutate(value = round(as.numeric(value),0))\n\nWarning: attributes are not identical across measure variables; they will be\ndropped\n\n# Change names of rows to question text\nq52_data &lt;- q52_data %&gt;% \n  gather(key=\"text\", value=\"value\") %&gt;%\n  # rename columns\n  mutate(text = gsub(\"Q52a_1\", \"In terms of questions I have about my life, my spirituality answers...\",text, ignore.case = TRUE)) %&gt;%\n  mutate(text = gsub(\"Q52b_1\", \"Growing spiritually is important...\",text, ignore.case = TRUE)) %&gt;%\n  mutate(text = gsub(\"Q52c_1\", \"When I&lt;e2&gt;&lt;80&gt;&lt;99&gt;m faced with an important decision, spirituality plays a role...\",text, ignore.case = TRUE)) %&gt;%\n  mutate(text = gsub(\"Q52d_1\", \"Spirituality is part of my life...\",text, ignore.case = TRUE)) %&gt;%\n  mutate(text = gsub(\"Q52e_1\", \"When I think of things that help me grow and mature as a person, spirituality has an effect on my personal growth...\",text, ignore.case = TRUE)) %&gt;%\n  mutate(text = gsub(\"Q52f_1\", \"My spiritual beliefs affect aspects of my life...\",text, ignore.case = TRUE))\n\n# Plot\n# Used for gradient colour schemes, as with violin plots\nlibrary(viridis) \n\nLoading required package: viridisLite\n\nq52_plot &lt;- q52_data %&gt;%\n  mutate(text = fct_reorder(text, value)) %&gt;% # Reorder data\n  ggplot( aes(x=text, y=value, fill=text, color=text)) +\n  geom_boxplot() +\n  scale_fill_viridis(discrete=TRUE, alpha=0.8) +\n  geom_jitter(color=\"black\", size=0.2, alpha=0.2) +\n  theme_ipsum() +\n  theme(legend.position=\"none\", axis.text.y = element_text(size = 8)) +\n  coord_flip() + # This switch X and Y axis and allows to get the horizontal version\n  xlab(\"\") +\n  ylab(\"Spirituality scales\") +\n  scale_x_discrete(labels = function(x) str_wrap(x, width = 45))\n\n# using gridExtra to specify explicit dimensions for printing\nq52_plot\n\n\n\nggsave(\"figures/q52_boxplot.png\", width = 20, height = 10, units = \"cm\")\n\nThere’s an enhanced version of this plot we can use, called ggstatsplot() to get a different view:\n\n# As an alternative trying ggstatsplot:\nlibrary(rstantools)\n\nThis is rstantools version 2.3.1.1\n\nlibrary(ggstatsplot)\n\nYou can cite this package as:\n     Patil, I. (2021). Visualizations with statistical details: The 'ggstatsplot' approach.\n     Journal of Open Source Software, 6(61), 3167, doi:10.21105/joss.03167\n\nq52_plot_alt &lt;- ggbetweenstats(\n  data = q52_data,\n  x = text,\n  y = value,\n  outlier.tagging  = TRUE,\n  title = \"Intrinsic Spirituality Scale Responses\"\n) +\n  scale_x_discrete(labels = function(x) str_wrap(x, width = 30)) +\n  # Customizations\n  theme(\n    # Change fonts in the plot\n    text = element_text(family = \"Helvetica\", size = 8, color = \"black\"),\n    plot.title = element_text(\n      family = \"Abril Fatface\", \n      size = 20,\n      face = \"bold\",\n      color = \"#2a475e\"\n    ),\n    # Statistical annotations below the main title\n    plot.subtitle = element_text(\n      family = \"Helvetica\", \n      size = 12, \n      face = \"bold\",\n      color=\"#1b2838\"\n    ),\n    plot.title.position = \"plot\", # slightly different from default\n    axis.text = element_text(size = 10, color = \"black\"),\n    axis.text.x = element_text(size = 7),\n    axis.title = element_text(size = 12),\n    axis.line = element_line(colour = \"grey50\"),\n    panel.grid.minor = element_blank(),\n    panel.grid.major.x = element_blank(),\n    panel.grid = element_line(color = \"#b4aea9\"),\n    panel.grid.major.y = element_line(linetype = \"dashed\"),\n    panel.background = element_rect(fill = \"#fbf9f4\", color = \"#fbf9f4\"),\n    plot.background = element_rect(fill = \"#fbf9f4\", color = \"#fbf9f4\")\n  )\n\nScale for x is already present.\nAdding another scale for x, which will replace the existing scale.\n\nq52_plot_alt\n\n\n\nggsave(\"figures/q52_plot_alt.png\", width = 20, height = 12, units = \"cm\")\n\nOne thing that might be interesting to test here is whether spirituality and religiosity are similar for our respondents.\n\nggplot(climate_experience_data, aes(x=Q52_score, y=Q57_1)) + labs(x=\"Spirituality Scale Score\", y = \"How Religious?\") +\n  geom_point(size=1, alpha=0.3) + geom_smooth(method=\"auto\", se=TRUE, fullrange=FALSE, level=0.95)\n\n`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = \"cs\")'\n\n\n\n\n# using http://sthda.com/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization\n\nggplot(climate_experience_data, aes(x=Q52_score, y=Q57_1)) +\n  labs(x=\"Spirituality Scale Score\", y = \"How Religious?\") +\n  geom_point(size=1, alpha=0.3) + stat_density_2d(aes(fill = ..level..), geom=\"polygon\", alpha=0.3)+\n  scale_fill_gradient(low=\"blue\", high=\"red\") +\n  theme_minimal()\n\nWarning: The dot-dot notation (`..level..`) was deprecated in ggplot2 3.4.0.\ni Please use `after_stat(level)` instead.\n\n\n\n\n\nBecause the responses to these two questions, about spirituality and religiosity are on a continuum, we can also use them, like we did in previous charts, to subset other datasets. A simple way of doing this is to separate our respondents into “high,” “medium,” and “low” bins for the two questions. Rather than working with hard values, like assigning 0-3, 4-6 and 7-10 for low medium and high, we’ll work with the range of values that respondents actually chose. This is particularly appropriate as the median answer to these questions was not “5”. So we’ll use the statistical concept of standard deviation, which R can calculate almost magically for us, in the following way:\n\n# Create low/med/high bins based on Mean and +1/-1 Standard Deviation\nclimate_experience_data &lt;- climate_experience_data %&gt;%\n  mutate(\n    Q52_bin = case_when(\n      Q52_score &gt; mean(Q52_score) + sd(Q52_score) ~ \"high\",\n      Q52_score &lt; mean(Q52_score) - sd(Q52_score) ~ \"low\",\n      TRUE ~ \"medium\"\n    ) %&gt;% factor(levels = c(\"low\", \"medium\", \"high\"))\n  )\n\n\n## Q57 subsetting based on Religiosity --------------------------------------------------------------\nclimate_experience_data &lt;- climate_experience_data %&gt;%\n  mutate(\n    Q57_bin = case_when(\n      Q57_1 &gt; mean(Q57_1) + sd(Q57_1) ~ \"high\",\n      Q57_1 &lt; mean(Q57_1) - sd(Q57_1) ~ \"low\",\n      TRUE ~ \"medium\"\n    ) %&gt;% factor(levels = c(\"low\", \"medium\", \"high\"))\n  )\n\nAs in the previous chapter, it’s useful to explore multiple factors when possible. So I’d like us to take the data about political affiliation to visualise alongside our religion and spirituality data. this will help us to see where effects are more or less significant and give us a point of comparison.\n\n## Q53 subsetting based on Political LR orientation --------------------------------------------------------------\n# Generate low/med/high bins based on Mean and SD\nclimate_experience_data &lt;- climate_experience_data %&gt;%\n  mutate(\n    Q53_bin = case_when(\n      Q53_1 &gt; mean(Q53_1) + sd(Q53_1) ~ \"high\",\n      Q53_1 &lt; mean(Q53_1) - sd(Q53_1) ~ \"low\",\n      TRUE ~ \"medium\"\n    ) %&gt;% factor(levels = c(\"low\", \"medium\", \"high\"))\n  )\n\nNow let’s use those bins to explore some of the responses about attitudes towards climate change:\n\n# Faceted plot working with 3x3 grid\ndf &lt;- select(climate_experience_data, Q52_bin, Q53_bin, Q57_bin, Q58)\nnames(df) &lt;- c(\"Q52_bin\", \"Q53_bin\", \"Q57_bin\", \"response\")\nfacet_names &lt;- c(`Q52_bin` = \"Spirituality\", `Q53_bin` = \"Politics L/R\", `Q57_bin` = \"Religiosity\", `low`=\"low\", `medium`=\"medium\", `high`=\"high\")\nfacet_labeller &lt;- function(variable,value){return(facet_names[value])}\ndf$response &lt;- factor(df$response, ordered = TRUE, levels = c(\"1\", \"2\", \"3\", \"4\", \"5\"))\ndf$response &lt;- fct_recode(df$response, \"More than once a week\" = \"1\", \"Once a week\" = \"2\", \"At least once a month\" = \"3\", \"Only on special holy days\" = \"4\", \"Never\" = \"5\")\ndf %&gt;% \n  # we need to get the data including facet info in long format, so we use pivot_longer()\n  pivot_longer(!response, names_to = \"bin_name\", values_to = \"b\") %&gt;% \n  # add counts for plot below\n  count(response, bin_name, b) %&gt;%\n  group_by(bin_name,b) %&gt;%\n  mutate(perc=paste0(round(n*100/sum(n),1),\"%\")) %&gt;% \n  # run ggplot\n  ggplot(aes(x = n, y = \"\", fill = response)) +\n  geom_col(position=position_fill(), aes(fill=response)) +\n  geom_text(aes(label = perc), position = position_fill(vjust=.5), size=2) +\n  scale_fill_brewer(palette = \"Dark2\", type = \"qual\") +\n  scale_x_continuous(labels = scales::percent_format()) +\n  facet_grid(vars(b), vars(bin_name), labeller=as_labeller(facet_names)) + \n  labs(caption = caption, x = \"\", y = \"\") + \n  guides(fill = guide_legend(title = NULL))\n\n\n\nggsave(\"figures/q58_faceted.png\", width = 30, height = 10, units = \"cm\")\n\n\n\n\n\n\n\n\n\nWhat is Religion?\n\n\n\nContent tbd\n\n\n\n\n\n\n\n\nHybrid Religious Identity\n\n\n\nContent tbd\n\n\n\n\n\n\n\n\nWhat is Secularisation?\n\n\n\nContent tbd"
  },
  {
    "objectID": "chapter_2.html#references",
    "href": "chapter_2.html#references",
    "title": "2  Survey Data: Spotlight Project",
    "section": "References",
    "text": "References"
  },
  {
    "objectID": "chapter_3.html#administrative-shapes---the-uk",
    "href": "chapter_3.html#administrative-shapes---the-uk",
    "title": "3  Mapping churches: geospatial data science",
    "section": "3.1 Administrative shapes - the UK",
    "text": "3.1 Administrative shapes - the UK\nA good starting point is to aquire some adminstrative data. This is a way of referring to political boundaries, whether country borders or those of a local authority or some other administrative unit. For our purposes, we’re going to import several different types of administrative boundary which will be used at different points in our visualisations below. It’s worth noting that the data we use here was prepared to support the 2011 census, and make use of the shapefile format.\n\nlibrary(sf) |&gt; suppressPackageStartupMessages()\nlibrary(here)  |&gt; suppressPackageStartupMessages()\nlibrary(tidyverse)  \n\n-- Attaching core tidyverse packages ------------------------ tidyverse 2.0.0 --\nv dplyr     1.1.3     v readr     2.1.4\nv forcats   1.0.0     v stringr   1.5.0\nv ggplot2   3.4.3     v tibble    3.2.1\nv lubridate 1.9.3     v tidyr     1.3.0\nv purrr     1.0.2     \n-- Conflicts ------------------------------------------ tidyverse_conflicts() --\nx dplyr::filter() masks stats::filter()\nx dplyr::lag()    masks stats::lag()\ni Use the conflicted package (&lt;http://conflicted.r-lib.org/&gt;) to force all conflicts to become errors\n\n# better video device, more accurate and faster rendering, esp. on macos. Also should enable system fonts for display\nlibrary(ragg) |&gt; suppressPackageStartupMessages()\n\nsetwd(\"/Users/kidwellj/gits/hacking_religion_textbook/hacking_religion\")\nhere::i_am(\"chapter_3.qmd\")\n\nhere() starts at /Users/kidwellj/gits/hacking_religion_textbook/hacking_religion\n\n# Download administrative boundaries for whole UK at country level\nif (file.exists(here(\"data\", \"infuse_uk_2011_clipped.shp\")) == FALSE) {\ndownload.file(\"https://borders.ukdataservice.ac.uk/ukborders/easy_download/prebuilt/shape/infuse_uk_2011_clipped.zip\", destfile = \"data/infuse_uk_2011_clipped.zip\")\nunzip(\"data/infuse_uk_2011_clipped.zip\", exdir = \"data\")\n}\nuk_countries &lt;- st_read(here(\"data\", \"infuse_uk_2011_clipped.shp\"), quiet = TRUE)\n\n# Download administrative boundaries for whole UK at regions level\nif (file.exists(here(\"data\", \"infuse_rgn_2011_clipped.shp\")) == FALSE) {\ndownload.file(\"https://borders.ukdataservice.ac.uk/ukborders/easy_download/prebuilt/shape/infuse_rgn_2011_clipped.zip\", destfile = \"data/infuse_rgn_2011_clipped.zip\")\nunzip(\"data/infuse_rgn_2011_clipped.zip\", exdir = \"data\")\n}\nuk_rgn &lt;- st_read(here(\"data\", \"infuse_rgn_2011_clipped.shp\"), quiet = TRUE)\n\n# Download administrative boundaries for whole UK at local authority level\nif (file.exists(here(\"data\", \"infuse_dist_lyr_2011_clipped.shp\")) == FALSE) {\ndownload.file(\"https://borders.ukdataservice.ac.uk/ukborders/easy_download/prebuilt/shape/infuse_dist_lyr_2011_clipped.zip\", destfile = \"data/infuse_dist_lyr_2011_clipped.zip\")\nunzip(\"data/infuse_dist_lyr_2011_clipped.zip\", exdir = \"data\")\n}\nlocal_authorities &lt;- st_read(here(\"data\", \"infuse_dist_lyr_2011_clipped.shp\"), quiet = TRUE)\n\n# Download building outlines for whole UK\nif (file.exists(here(\"data\", \"infuse_dist_lyr_2011_simplified_100m_buildings_simplified.gpkg\")) == FALSE) {\n  download.file(\"https://zenodo.org/record/6395804/files/infuse_dist_lyr_2011_simplified_100m_buildings_overlay_simplified.gpkg\", destfile = here(\"data\", \"infuse_dist_lyr_2011_simplified_100m_buildings_simplified.gpkg\"))}\nlocal_authorities_buildings_clip &lt;- st_read(here(\"data\", \"infuse_dist_lyr_2011_simplified_100m_buildings_simplified.gpkg\"), quiet = TRUE)\n\nBefore we move on, let’s plot a simple map and have a look at one of our administrative layers. We can use ggplot with a new type of shape geom_sf() to plot the contents of a geospatial data file with polygons which is loaded as a simplefeature in R.\n\nggplot(uk_countries) + geom_sf()"
  },
  {
    "objectID": "chapter_3.html#load-in-ordnance-survey-openmap-points-data",
    "href": "chapter_3.html#load-in-ordnance-survey-openmap-points-data",
    "title": "3  Mapping churches: geospatial data science",
    "section": "3.2 Load in Ordnance Survey OpenMap Points Data",
    "text": "3.2 Load in Ordnance Survey OpenMap Points Data\n\n# Note: for more advanced reproducible scripts which demonstrate how these data surces have been \n# obtained, see the companion cookbook here: https://github.com/kidwellj/hacking_religion_cookbook/blob/main/ordnance_survey.R\n\nos_openmap_pow &lt;- st_read(here(\"data\", \"os_openmap_pow.gpkg\"), quiet = TRUE)\n\nggplot(os_openmap_pow) + geom_sf()\n\n\n\n\nIt’s worth noting that the way that you load geospatial data in R has changed quite dramatically since 2020 with the introduction of the simplefeature class in R. Much of the documentation you will come across “out there” will make reference to a set of functions which are now deprecated.\nLet’s use that data we’ve just loaded to make our first map:\n\n# Generate choropleth map of respondent locations\n# using temporary palette here so that 0s are white\nlibrary(tmap) |&gt; suppressPackageStartupMessages()\n# palette &lt;- c(white, \"#a8ddb5\", \"#43a2ca\")\n\nmap1 &lt;- tm_shape(local_authorities) + \n#  tm_fill(col = \"surveys_count\", , palette = palette, title = \"Concentration of survey respondents\") +\n  tm_borders(alpha=.5, lwd=0.1) +\n  # for intermediate polygon geometries\n  # tm_shape(local_authorities) +\n  # tm_borders(lwd=0.6) +\n  # for dots from original dataset\n  # tm_dots(\"red\", size = .05, alpha = .4) +\n  tm_scale_bar(position = c(\"right\", \"bottom\")) +\n  tm_style(\"gray\") +\n  tm_credits(\"Data: UK Data Service (OGL)\\n& Jeremy H. Kidwell,\\nGraphic is CC-by-SA 4.0\", \n             size = 0.4, \n             position = c(\"left\", \"bottom\"),\n             just = c(\"left\", \"bottom\"),\n             align = \"left\") +\n  tm_layout(asp = NA,\n            frame = FALSE, \n            title = \"Figure 1a\", \n            title.size = .7,\n            legend.title.size = .7,\n            inner.margins = c(0.1, 0.1, 0.05, 0.05)\n  )\n\nmap1\n\n\n\n# save image\ntmap_save(map1, here(\"figures\", \"map.png\"), width=1920, height=1080, asp=0)\n\nMap saved to /Users/kidwellj/gits/hacking_religion_textbook/hacking_religion/figures/map.png\n\n\nResolution: 1920 by 1080 pixels\n\n\nSize: 6.4 by 3.6 inches (300 dpi)\n\n\n\n# subsetting ordnance survey openmap data for measuring clusters and proximity\n\nos_openmap_important_buildings &lt;- st_read(here(\"data\", \"os_openmap_important_buildings.gpkg\"), quiet = TRUE)\n\n# add pubs, check_cashing, pawnbrokers, SSSI\n## subsets\n\n\nCount the number of churches in Local Authorities\n\n\n# OSM data\n\n# Note: for more advanced reproducible scripts which demonstrate how these data surces have been \n# obtained, see the companion cookbook here: https://github.com/kidwellj/hacking_religion_cookbook/blob/main/ordnance_survey.R\n\n\n# osm_uk_points &lt;- st_read(system.file(here(\"data\", \"pow_osm.gpkg\", package = \"spData\")))\n# vector_filepath = system.file(\"data/osm-gb-2018Aug29_pow_osm.pbf\", package = \"sf\")\n# osm_uk_points = st_read(vector_filepath)\n\nGuides to geographies: https://rconsortium.github.io/censusguide/ https://ocsi.uk/2019/03/18/lsoas-leps-and-lookups-a-beginners-guide-to-statistical-geographies/\nCalculate proximity to pubs"
  },
  {
    "objectID": "chapter_3.html#references",
    "href": "chapter_3.html#references",
    "title": "3  Mapping churches: geospatial data science",
    "section": "References",
    "text": "References"
  },
  {
    "objectID": "chapter_4.html",
    "href": "chapter_4.html",
    "title": "4  Data scraping, corpus analysis and wordclouds",
    "section": "",
    "text": "References"
  },
  {
    "objectID": "chapter_5.html",
    "href": "chapter_5.html",
    "title": "5  What’s next?",
    "section": "",
    "text": "References"
  },
  {
    "objectID": "chapter_5.html#how-to-get-more-data",
    "href": "chapter_5.html#how-to-get-more-data",
    "title": "5  What’s next?",
    "section": "5.1 How to get more data",
    "text": "5.1 How to get more data\nData can come from a wide variety of places"
  },
  {
    "objectID": "chapter_5.html#how-to-get-help",
    "href": "chapter_5.html#how-to-get-help",
    "title": "5  What’s next?",
    "section": "5.2 How to get help",
    "text": "5.2 How to get help\nOnline forums Etiquette"
  },
  {
    "objectID": "summary.html",
    "href": "summary.html",
    "title": "6  Summary",
    "section": "",
    "text": "An open textbook introducing data science to religious studies"
  }
]