Posted on

moRe aRchaeology

Using R to visualise Archaeological data.

I like R, the computer language focussed on data analysis, and I like Archaeology (which may come as a surprise to all the people who have heard me complain about my job, but that’s another matter entirely). So, in my ongoing mission to learn how to use R properly it makes sense that I would be trying to use it for archaeological ends. You can’t beat a nice visualisation of a massive and borderline unreadable spreadsheet that makes it so much easier to pull out patterns and correlations from the data.

One of the problems that I have come across with learning R is finding suitable data-sets for me to work from. Archaeologists are very very very bad at publishing their raw data so that others can carry out analysis in order to see if their results can be replicated. Archaeology, by dint of how we recover data in the form of excavation, is an inherently destructive process. A site cannot be excavated twice. Especially not if, after the first time it was excavated, it was then buried underneath a new road or housing development. Which is exactly what happens to the vast majority of archaeological sites which are excavated being as most archaeological excavation is carried out prior to a new building project of on kind or another.

Which is why it is extremely important that archaeological data is shared so that other archaeologists can use the data recovered and thus drive the discipline forward. Unfortunately this is not always the case and the raw data from an excavation can sit indefinitely in the archives of the local heritage authority or on the hard-drives of the excavation firm who carried out the work. This is especially the case in the region where I work, Niedersachsen/Bremen, where almost no archaeological data is publicly available (outside of the god-awful ‘Denkmal-Atlas’ which may be nice for lay people, not so great for carrying out scientific work) and one must request any data from the authorities.

I am loath to go through the process of asking the local authorities for data when it is, mostly, just for me to faff around with whilst I learn a new programming language. When I have a decent research proposal then maybe. But, for now, I am having to try and find open data sources online.

There are some places where data can be found such as the Journal of Open Archaeology Data or the Archaeological Data Service but they rarely, if ever, contain data from Germany. Germany is something of a black hole when it comes to archaeological data. So I was rather happy when I found out that Kiel University has an online space for post-graduate students to deposit their data.

Naturally I downloaded everything I could get my grubby little hands on. Which then led me on to a revelation, something that I suppose I have down for a long time, that we archaeologists really really bloody suck at organising data…

We can’t really be blamed for that I suppose. After all, we were never taught data management in university! And if we were, it was probably by someone who was an archaeologist who self learned a bit of data management on the side. (A bit like I am doing with R) Rather than being taught by an actual data scientist.

(I know that some archaeologists will have learned properly, I am just going of my own experience at university. Oh, and through knowing a lot of archaeologists who also suck at this stuff.)

Rant over and on to the really nerdy stuff.

As part of learning R I am wanting to learn how to process data into a way that I can use for visualisation. Part of this will involve cleaning the data (just as well that archaeologists are messy so-and-sos) and then using R to generate a variety of visualisation which can then be used to analyse the data.

The data set that I chose to play with today comes from the paper Loom Weights in Bronze Age Central Europe by Jutta Kneisel and Stefanie Schaefer-Di Maida from in the book The Textile Revolution in Bronze Age Europe. Production, Specialisation, Consumption by Serena Sabatini and Sophie Bergerbrant(Eds.)

The data was issued under a Creative Commons CC BY-NC-SA license, and therefore so is this wee blog post.

Before I start, I want to make clear that I may well cuss and moan about the data that I downloaded, but that is in no way a comment on the work of the authors. Merely on the way that they have arranged their data. Which, as I just said, isn’t the sort of thing that most archaeologists are trained in and I deeply appreciate that they made their data available for all.

The below is 99% just so that I can remember the process at a later date or have something to refer back to.

Method

Step 1 – Get the data and import it into RStudio

First off, download the data from here and extract it into your project folder. Within the .zip file is an Excel workbook (first complaint, please don’t use Excel it has a really bad habit of thinking that it is cleverer than you and so adjusts the format of the cells, as we shall come back to.) The .zip also contains the really nice visualisations which Kneisel and Schaefer-Di Maida created for their chapter.

An Excel workbook may seem like a sensible option for storing your data, after all – one file can contain several spreadsheets meaning that you don’t have to have multiple things open on your computer at a time. It isn’t however a future proof way to archive data, try opening a Word doc from 1995 and see what I mean, and there is also the above mentioned problem.

So, the first thing I need to do is export each sheet as a .csv. A .csv is an extremely basic way of storing data. It is columns and rows like a spreadsheet but with the ‘columns’ being divided by a comma. (Comma Separated Values, csv) It is also simply a text file, meaning that any text editing program can open it, on any platform, and it doesn’t matter if the file was created in 1995 or 2095.

So, with each sheet as an individual .csv into my project folder, I can begin getting the data into Rstudio.

To do this I use the read.csv function of R. The format of the command is as follows.

cyl <- read.csv(“Loomweights_cylindrical.csv”)
disc <- read.csv(“Loomweights_disc-shaped.csv”)
others <- read.csv(“Loomweights_others.csv”)
pyra <- read.csv(“Loomweights_pyramidal.csv”)
ring <- read.csv(“Loomweights_ring-shaped.csv”)
sph <- read.csv(“Loomweights_spherical.csv”)
tri <- read.csv(“Loomweights_triangle.csv”)

What this does is tell R to read the .csv files and store them as dataframes with the first word in each command being the name of the dataframe. <- being something like ‘=’ but if R saw ‘=’ it would look for ‘cyl’ and, not finding it because it hasn’t been created yet, throw an error.

To check that the dataframes have been created correctly we can use the ‘head’ command to print the first few lines from the data table. Here are the results of > head(cyl)

  id                    site  site.Nr.         x        y number.of.weights minimum.number.of.weights Gewicht Gewicht_N
1  1                Allstedt       E10 11.392681 51.43134                 1                         1                NA
2  2 Alt Gaul OT von Wriezen           14.097146 52.73958                 1                         1                NA
3  3           Arbon Bleiche 7, Fpl. 2  9.431606 47.51672                23                        23    1800      1800
4  4               Archlebov           17.003932 49.04341                 1                         1                NA
5  5          Aub-Burgerroth           10.031506 49.53399                 1                         1                NA
6  6             B6N_Fundst.     VII 2 11.118200 51.81700                 1                         1                NA
  district.parish        country        type ornamented puncture.outside finger.dents Cross lines.outside
1    Sangerhausen Sachsen-Anhalt zylindrisch   verziert                                                  
2                    Brandenburg                                                                         
3     Kt. Thurgau        Schweiz zylindrisch   verziert                             x                    
4    okr. Hodonín     Tschechien  o. Angaben                                                             
5        Würzburg         Bayern zylindrisch   verziert                                                 x
6                 Sachsen-Anhalt zylindrisch                                                             
  ornamentation.remarks find.context remarks          period
1                         Einzelfund                        
2                           Siedlung                        
3                           Siedlung                        
4                           Siedlung          Verterov Grppe
5     zwei Linien außen     Siedlung         Kupferzeitlich?
6                                     Walze?                
                                                                      literature Chronology length width.cross.section
1                                                                      Zich 1996        FBZ                           
2                                                               Fundortdatenbank                                      
3 Gleser 2007, Hochuli 1994, Taf. 80, 734-36; Taf. 81, 744-745; Taf. 82, 750-751        FBZ                           
4                                                                    Gleser 2007        FBZ                           
5                                                                    Gleser 2007 Kupferzeit                           
6                                                          mündl. Mitt. C. Rinne         BZ                           
   X  X.1        X.2 X.3 X.4 X.5         X.6 X.7
1 NA                  NA  NA  NA                
2 NA                  NA  NA  NA                
3 NA                  NA  NA  NA                
4 NA                  NA  NA  NA                
5 NA                  NA  NA  NA                
6 NA nein Webgewicht  NA   4  36 0,02- Sohle  

The data is all there, but it is still pretty messy.

What I would like to do with R is create some visualisations to see if there is any correlation between the shape of the Loom Weights and the region in which they are found. Are styles of loom weight a local thing (for local people!). To this end, I would like to combine all of the data-frames into a single data-frame so that I am only having to refer to a single data-frame in my code, making it a lot easier to read and understand. To do this I will need to use ‘dplyr’ which is a powerful tool for data manipulation in R.

What I want to do is create a new data-frame, let’s call it ‘loom_weights’, but I only want the data from a handful of the columns in the .csv files. I don’t need, for example, the literature relating to the site or the dimensions of the weights themselves. So I need to tell dplyr what data to take and from which dataframes.

First I will make a list of the data-frames that I would like to extract data from.

And this, I do thus:

dfs <- list(cyl, disc, others, pyra, ring, sph, tri)

This creates a list of all the data-frames. Next I need to tell R what I want the new data-frame to be called and which frames, from the list, to work on.

And this, I do thus:

loom_weights <- bind_rows(lapply(dfs, function(df) {
df %>% select(site, site.Nr., x, y, number.of.weights, type, ornamented, find.context, period, remarks, Chronology)
}))

Except that I don’t as R immediately throws errors due to the formatting of the data. You see, computer languages (well, the two with which I am familiar, R and Python) like data in columns to all be of the same sort. So, all strings (strings of characters), integers (whole numbers), real (decimal numbers), dates, and so on. The problem that we have here is threefold. First, there are some entries in the columns that contain no data and so have the value ‘NA’ which is a pain if R expects that to be a column of numbers. So we need to replace those ‘NA’ with ‘0’.

Then there are the Site Numbers. Some of these are numeric, some are just letters, and others are a mix. Therefore I have to tell R to treat the Site.Nr column as a string. Luckily we don’t have to do any calculations with the values in the Site.Nr column, so it is ok to treat them as strings. (You can’t do mathematical calculations with strings, only with real numbers or integers).

site.Nr. = as.character(site.Nr.)

We also have the problem that I mentioned earlier, where Excel thinks that it is clever. Some of the values in the ‘x’ column have been converted to a date format…

Replacing NA with 0 is pretty easy, we just adjust our code like so:

loom_weights <- bind_rows(lapply(dfs, function(df) {
df %>%
select(site, site.Nr., x, y, number.of.weights, type, ornamented, find.context, period, remarks, Chronology) %>%
mutate(across(everything(), ~ ifelse(is.na(.), 0, .))) # Replace NA with 0
}))

Here we use %>% to pipe the selected data through the mutate function which seeks out all instances of NA and replaces them with 0.

Sorting out the date issue is a bit more tricky.

I could, and probably should, go through the spreadsheet in Excel and ensure that all cells containing coordinates are set to display the numbers as they were entered, not as Excel thinks that they should be. But, this is about R and learning so let’s try and do it another way.

First I create a function to clean up the entries that are formatted as dates back to real numbers. I am going to be making a huge assumption here in that the first two digits of the value should be followed by a dot rather than a slash and that the second slash should simply be discarded. What could go wrong eh?

clean_date_format <- function(column) {
column <- as.character(column) # Ensure it’s a character type
column <- gsub(“^([0-9]{2})/([0-9]{2})/[0-9]{4}$”, “\\1.\\2”, column) # Replace format
return(column)
}

This function can then be called upon later in the code when the data is being processed.

So, here is the final code for tidying up the dataframes into a single dataframe and dealing with NA values, strings where there should be integers, and getting rid of those pesky dates.

loom_weights <- bind_rows(lapply(dfs, function(df) {
df %>%
select(site, site.Nr., x, y, number.of.weights, type, ornamented, find.context, period, remarks, Chronology) %>%
mutate(
# Convert ‘site.Nr.’ to character (string) type
site.Nr. = as.character(site.Nr.),
# Clean the ‘x’ and ‘y’ columns for date-like entries
x = clean_date_format(x),
y = clean_date_format(y),
# Convert ‘x’ and ‘y’ back to numeric (after cleaning), replacing non-numeric with NA
x = as.numeric(x),
y = as.numeric(y),
# Convert ‘number.of.weights’ to numeric, replacing non-numeric entries with NA
number.of.weights = as.numeric(number.of.weights),
# Replace NA with 0 in numeric columns
across(where(is.numeric), ~ ifelse(is.na(.), 0, .)),
# Replace NA with an empty string in character columns
across(where(is.character), ~ ifelse(is.na(.), “”, .))
)
}))

There, that should work. And it does!

I have a data-frame called ‘loom_weights’ and head(loom_weights) gives me the following.

   site  site.Nr.         x        y number.of.weights        type ornamented find.context
1                Allstedt       E10 11.392681 51.43134                 1 zylindrisch   verziert   Einzelfund
2 Alt Gaul OT von Wriezen           14.097146 52.73958                 1                            Siedlung
3           Arbon Bleiche 7, Fpl. 2  9.431606 47.51672                23 zylindrisch   verziert     Siedlung
4               Archlebov           17.003932 49.04341                 1  o. Angaben                Siedlung
5          Aub-Burgerroth           10.031506 49.53399                 1 zylindrisch   verziert     Siedlung
6             B6N_Fundst.     VII 2 11.118200 51.81700                 1 zylindrisch                        
           period remarks Chronology         z_x         z_y
1                                FBZ -0.08057198  0.30016554
2                                     0.44291980  0.42501876
3                                FBZ -0.46016892 -0.07343182
4  Verterov Grppe                FBZ  1.00557400  0.07227032
5 Kupferzeitlich?         Kupferzeit -0.34404883  0.11908927
6                  Walze?         BZ -0.13370210  0.33697113

Step 2 – Visualisation

OK, let’s start making pretty visualisations of the data.

First we need to install the necessary packages into R, in this case we will be using ggplotly for data visualisation.

install.packages(“ggplot2”)
library(ggplot2)

will install and load the packages.

To make a simple scatterplot we use the following:

ggplot(loom_weights, aes(x = x, y = y, color = type)) +
geom_point(size = 3, alpha = 0.7) +
theme_minimal() +
labs(title = “Geographic Location of Loom Weights by Type”,
x = “X Coordinate”,
y = “Y Coordinate”,
color = “Type”)

This will use ggplotly to read loom_weights and use the x and y values from those columns to plot each point on a Cartesian grid. ‘color = type’ says that each point is to have its colour defined by the value in the ‘type’ column. ‘geom_point’ defines how the points themselves will look and ‘labs’ refers to the labels of the plot.

And this is what we get.

 

Hmmmm, that I doesn’t look too great. Not too shabby, but not too great. But we also have those strange outliers that look to be very far away from the study area. I get the strange feeling that these are the sites where the coordinates were in date format. What can go wrong eh?

Well, I’m not going to go back through and try to fix them at the moment. So I need to figure out which of the rows are so far away from the study area and I shall do this using the standard deviation of all points and exclude any that are too far outside of the SD.

We do this by calculating the Z value for each point and filtering out any rows where the Z score is way outside the SD for the plot.

loom_weights <- loom_weights %>%
mutate(z_x = (x – mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE),
z_y = (y – mean(y, na.rm = TRUE)) / sd(y, na.rm = TRUE))
# Filter out rows where the z-score is outside the range of [-3, 3] for either x or y
loom_weights_filtered <- loom_weights %>%
filter(abs(z_x) <= 3 & abs(z_y) <= 3)
# Remove the z_x and z_y columns after filtering
loom_weights_filtered <- loom_weights_filtered %>%
select(-z_x, -z_y)

That looks much better! There are however a bunch of ‘type’ values there that we don’t really need. If I am wanting to see whether there is a geographic correlation between the forms of loom weight I don’t need ones where there is no description of the form (ohne Angabe/n in this case) or where it is a sherd that has a hole drilled through it (durchbohrte Bodenscherbe) or if it is just a fragment of a loom weight.

So, let’s filter these rows out and see what we get.

#using ‘c’ to create a vector containing the rows to be filtered out
excluded_types <- c(‘Fragment’, ‘durchbohrte Bodenscherbe’, ‘o, Angaben’, ‘o. Angabe’, ‘o. Angaben’, ‘o. Angaben, verziert’)
# Filter out rows where ‘type’ is one of the excluded values
loom_weights_type_filtered <- loom_weights_filtered %>%
filter(!(type %in% excluded_types))
# Display the filtered dataframe
head(loom_weights_type_filtered)
#Same code as previously but for the new dataframe
ggplot(loom_weights_type_filtered, aes(x = x, y = y, color = type)) +
geom_point(size = 3, alpha = 0.7) +
theme_minimal() +
labs(title = “Geographic Location of Loom Weights by Type”,
x = “X Coordinate”,
y = “Y Coordinate”,
color = “Type”)

You will see from the previous snippets of code that we are creating more and more data-frames as we go on. This means that if… lol, when I mess something up I can always roll back and work on a previous data-frame.

Let’s see how it looks.

Super! That is much better and less cluttered by data points which aren’t going to help us see what we want to see.

We can defiitely see something of a pattern here, but the colours of the points are all so similar that it is difficult to tell whether a point is pyramidal or oval.

There is a package for R called viridis which may give us a colour palette with more contrast.

install.packages(“viridis”)
library(viridis)
ggplot(loom_weights_type_filtered, aes(x = x, y = y, color = type)) +
geom_point(size = 3, alpha = 0.7) +
scale_color_viridis(discrete = TRUE) + # Use the viridis palette
theme_minimal() +
labs(title = “Geographic Location of Loom Weights by Type”,
x = “X Coordinate”,
y = “Y Coordinate”,
color = “Type”)

Hmmm, better, but not quite there yet.

Let’s try a way to define the boundaries of the various types by drawing ovals around them.

library(ggplot2)
library(viridis)

# Plot with ellipses and a single legend
ggplot(loom_weights_type_filtered, aes(x = x, y = y, color = type)) +
geom_point(size = 3, alpha = 0.7) +
stat_ellipse(aes(fill = type), geom = “polygon”, alpha = 0.2, color = NA, show.legend = FALSE) + # Add ellipses without separate legend
scale_color_viridis(discrete = TRUE) + # Use distinct color palette for both
scale_fill_viridis(discrete = TRUE, guide = “none”) + # Ensure fill uses same color and hide the fill legend
theme_minimal() +
labs(title = “Geographic Location of Loom Weights by Type”,
x = “X Coordinate”,
y = “Y Coordinate”,
color = “Type”)

Hmmm, better but also not great. But I think that will do for now. Next time I may try making something a bit more interactive and see if that helps. Or perhaps laying the points across a map….