\documentclass[12pt]{memoir}

% % article-1 and article-2 styles were originally based on kieran healy's
% templates
\usepackage{mako-mem}
\chapterstyle{article-2}

% with article-3 \chapterstyle, change to: \pagestyle{memo}
\pagestyle{mako-mem}


\usepackage[utf8]{inputenc}

\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage[garamond]{mathdesign}

\usepackage[letterpaper,left=1.65in,right=1.65in,top=1.3in,bottom=1.2in]{geometry}

<<init, echo=FALSE, message=FALSE>>=
knit_hooks$set(document = function(x) {
  sub('\\usepackage[]{color}',
'\\usepackage[usenames,dvipsnames]{color}', x, fixed = TRUE)
})
#$
@

% packages I use in essentially every document
\usepackage{graphicx}
\usepackage{enumerate}

% packages i use in many documents but leave off by default
% \usepackage{amsmath, amsthm, amssymb}
% \usepackage{dcolumn}
% \usepackage{endfloat}

% import and customize urls
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[breaklinks]{hyperref}

\hypersetup{colorlinks=true, linkcolor=Black, citecolor=Black, filecolor=Blue,
    urlcolor=Blue, unicode=true}

% list of footnote symbols for \thanks{}
\makeatletter
\renewcommand*{\@fnsymbol}[1]{\ensuremath{\ifcase#1\or *\or \dagger\or \ddagger\or
 \mathsection\or \mathparagraph\or \|\or **\or \dagger\dagger
  \or \ddagger\ddagger \else\@ctrerr\fi}}
\makeatother
\newcommand*\samethanks[1][\value{footnote}]{\footnotemark[#1]}

% add bibliographic stuff 
\usepackage[american]{babel}
\usepackage{csquotes}
\usepackage[natbib=true, style=apa, backend=biber]{biblatex}
\addbibresource{refs.bib}
\DeclareLanguageMapping{american}{american-apa}

\defbibheading{secbib}[\bibname]{%
  \section*{#1}%
  \markboth{#1}{#1}%
  \baselineskip 14.2pt%
  \prebibhook}

\def\citepos#1{\citeauthor{#1}'s (\citeyear{#1})}
\def\citespos#1{\citeauthor{#1}' (\citeyear{#1})}

% memoir function to take out of the space out of the whitespace lists
\firmlists


% LATEX NOTE: these lines will import vc stuff after running `make vc` which
% will add version control information to the bottom of each page. This can be
% useful for keeping track of which version of a document somebody has:
\input{vc}
\pagestyle{mako-mem-git}

% LATEX NOTE: this alternative line will just input a timestamp at the
% build process, useful for sharelatex
%\pagestyle{mako-mem-sharelatex}

\setlength{\parskip}{4.5pt}
% LATEX NOTE: Ideal linespacing is usually said to be between 120-140% the
% typeface size. So, for 12pt (default in this document, we're looking for
% somewhere between a 14.4-17.4pt \baselineskip.  Single; 1.5 lines; and Double
% in MSWord are equivalent to ~117%, 175%, and 233%.

% packages specific to /this/ to document
\usepackage{adjustbox}
\usepackage{longtable}
% \usepackage{lmodern}

\definecolor{snagrey1}{HTML}{D9D9D9}
\definecolor{snagrey2}{HTML}{BDBDBD}
\definecolor{snagrey3}{HTML}{969696}
\definecolor{snagrey4}{HTML}{737373}
\definecolor{snagrey5}{HTML}{525252}
\definecolor{snagrey6}{HTML}{252525}

% Prefix table and figure numbers with our chapter number
\renewcommand{\thetable}{6.\arabic{table}}   
\renewcommand{\thefigure}{6.\arabic{figure}}

\begin{document}

<<import data, echo=FALSE, message=FALSE>>=
library(dplyr)
library(ggplot2)
library(xtable)
library(data.table)
library(reshape2)
library(plyr)

bold <- function(x) {paste('{\\textbf{',x,'}}', sep ='')}
gray <- function(x) {paste('{\\textcolor{gray}{',x,'}}', sep ='')}
wrapify <- function (x) {paste("{", x, "}", sep="")}

f <- function (x) {formatC(x, format="d", big.mark=',')}

load("data/orig_data_sets.RData")
load("data/topic_model_data.RData")
load("data/prediction_descriptives.RData")
load("data/prediction.RData")

load("data/network_data.RData")
attach(r)
@

\baselineskip 16pt

\title{A Computational Analysis of Social Media Scholarship}

\author{Jeremy Foote (\href{mailto:jdfoote@u.northwestern.edu}{jdfoote@u.northwestern.edu})
        
        \smallskip
		
		Aaron Shaw (\href{mailto:aaronshaw@northwestern.edu}{aaronshaw@northwestern.edu})
		
		\smallskip
		
		Benjamin Mako Hill (\href{mailto:makohill@uw.edu}{makohill@uw.edu})
}
\date{}

\published{\textcolor{BrickRed}{\textsc{This is the final authors' version of a published book chapter. When citing this work, please cite the published version:} Foote, Jeremy D., Aaron Shaw, and Benjamin Mako Hill. 2017. “A Computational Analysis of Social Media Scholarship.” In \textit{The SAGE Handbook of Social Media}, edited by Jean Burgess, Alice Marwick, and Thomas Poell, 111–34. London, UK: SAGE.}}

\maketitle

\vspace{-2.5em}

\begin{abstract}
Data from social media platforms and online communities have fueled the growth of computational social science. In this chapter, we use computational analysis to characterize the state of research on social media and demonstrate the utility of such methods. First, we discuss how to obtain datasets from the APIs published by many social media platforms. Then, we perform some of the most widely used computational analyses on a dataset of social media scholarship we extract from the Scopus bibliographic database's API. We apply three methods: network analysis, topic modeling using latent Dirichlet allocation, and statistical prediction using machine learning. For each technique, we explain the method and demonstrate how it can be used to draw insights from our dataset. Our analyses reveal overlapping scholarly communities studying social media. We find that early social media research applied social network analysis and quantitative methods, but the most cited and influential work has come from marketing and medical research. We also find that publication venue and, to a lesser degree, textual features of papers explain the largest variation in incoming citations. We conclude with some consideration of the limitations of computational research and future directions.

\end{abstract}

\section{Introduction}

The combination of large-scale trace data generated through social media with a series of advances in computing and statistics have enabled the growth of `computational social science' \citep{lazer_computational_2009}. This turn presents an unprecedented opportunity for researchers who can now test social theories using massive datasets of fine-grained, unobtrusively collected behavioral data. In this chapter, we aim to introduce non-technical readers to the promise of these computational social science techniques by applying three of the most common approaches to a bibliographic dataset of social media scholarship. We use our analyses as a context for discussing the benefits of each approach as well as some of the common pitfalls and dangers of computational approaches.

The chapter walks through the entire process of computational analysis, beginning with data collection. We explain how we gather a large-scale dataset about social media research from the \emph{Scopus} website's application programming interface. In particular, our dataset contains data about every article in the Scopus database that includes the term `social media' in its title, abstract, or keywords. Using this dataset, we perform multiple computational analyses. First, we use network analysis \citep{wasserman_social_1994} on article citation metadata to understand the structure of references between the articles. Second, we use topic models \citep{blei_probabilistic_2012}, an unsupervised natural language processing technique, to describe the distribution of topics within the sample of articles included in our analysis. Third, we perform statistical prediction \citep{james_introduction_2013} in order to understand what characteristics of articles best predict subsequent citations. For each analysis, we describe the method we use in detail and discuss some of its benefits and limitations.

Our results reveal several patterns in social media scholarship. Bibliometric network data reveals disparities in the degree that disciplines cite each other and illustrate that marketing and medical research each enjoy surprisingly large influence. Through descriptive analysis and topic modeling, we find evidence of the early influence of social network research. When we use papers' characteristics to predict which work gets cited, we find that publication venues and linguistic features provide the most explanatory power.

In carrying out our work in this chapter, we seek to exemplify several current best practices in computational research. We use data collected in a manner consistent with the expectations of privacy and access held by the subjects of our analysis as well as the publishers of the data source. We also make our analysis fully reproducible from start to finish. In an online supplement, we provide the full source code for all aspects of this project -- from the beginning of data collection to the creation of the figures and the chapter text itself -- as a resource for future researchers.

\section{Collecting and describing data from the web}

A major part of computational research consists of obtaining data, preparing it for analysis, and generating initial descriptions that can help guide subsequent inquiry. Social media datasets vary in how they make it into researchers' hands. There are several sources of social media data which are provided in a form that is pre-processed and ready for analysis. For example, The Stanford Large Network Dataset Collection \citep{leskovec_snap_2014} contains pre-formatted and processed data from a variety of social media platforms. Typically, prepared datasets come formatted as `flat files' such as comma-separated value (CSV) tables, which many types of statistical software and programming tools can import directly.

More typically, researchers retrieve data directly from social media platforms or other web-based sources. These `primary' sources provide more extensive, dynamic, and up-to-date datasets, but also require much more work to prepare the data for analysis. Typically, researchers retrieve these data from social media sites through application programming interfaces (APIs). Web sites and platforms use APIs to provide external programmers with limited access to their servers and databases. Unfortunately, APIs are rarely designed with research in mind and are often inconvenient and limited for social scientists as a result. For example, Twitter's search API returns a small, non-random sample of tweets by default (what a user might want to read), rather than all of the tweets that match a given query (what a researcher building a sample would want). In addition, APIs typically limit how much data they will provide for each query and how many queries can be submitted within a given time period.

APIs provide raw data in formats like XML or JSON, which are poorly suited to most data analysis tasks. As a result, researchers must take the intermediate step of converting data into more appropriate formats and structures. Typically, researchers must also construct measures from the raw data, such as user-level statistics (e.g., number of retweets) or metadata (e.g., post length). A number of tools, such as NodeXL \citep{hansen_analyzing_2010}, exist to make the process of obtaining and preparing digital trace data easier. However, off-the-shelf tools tend to come with their own limitations and, in our experience, gathering data amenable to computational analysis usually involves some programming work. 

Compared to some traditional forms of data collection, obtaining and preparing social media data has high initial costs. It frequently involves writing and debugging custom software, reading documentation about APIs, learning new software libraries, and testing datasets for completeness and accuracy. However, computational methods scale very well and gathering additional data often simply means expanding the date range in a programming script. Contrast this with interviews, surveys, or experiments, where recruitment is often labor-intensive, expensive, and slow. Such scalability, paired with the massive participation on many social media platforms, can support the collection of very large samples.

\subsection{Our application: The Scopus Bibliographic Database}

We used a series of Scopus Bibliographic Database APIs to retrieve data about all of the publications in their database that contained the phrase `social media' in their abstract, title, or keywords. We used the Python programming language to write custom software to download data. First, we wrote a program to query the Scopus Search API to retrieve a list of the articles that matched our criteria. We stored the resulting list of \Sexpr{f(total.articles)} articles in a file. We used this list of articles as input to a second program, which used the Scopus Citations Overview API to retrieve information about all of the articles that cited these \Sexpr{f(total.articles)} articles. Finally, we wrote a third program that used the Scopus Abstract Retrieval API to download abstracts and additional metadata about the original \Sexpr{f(total.articles)} articles. Due to rate limits and the process of trial and error involved in writing, testing, and debugging these custom programs, it took a few weeks to obtain the complete dataset.

Like many social media APIs, the Scopus APIs returns data in JSON format. Although not suitable for analysis without processing, we stored this JSON data in the form it was given to us. Retaining the `raw' data directly from APIs allows researchers to construct new measures they might not have believed were relevant in the early stages of their research and to fix any bugs that they find in their data processing and reduction code without having to re-download raw data. Once we obtained the raw data, we wrote additional Python scripts to turn the downloaded JSON files into CSV tables which could be imported into Python and R, the programming languages we used to complete our analyses.

\subsection{Results}

The Scopus dataset contains a wide variety of data, and many different descriptive statistics could speak to various research questions. Here we present a sample of the sorts of summary data that computational researchers might explore. We begin by looking at where social media research is produced. Table \ref{tab:country} shows the number of papers produced by authors located in each of the six most frequently seen countries in our dataset.\footnote{Technically, each paper is assigned to the modal (i.e.,~most frequent) country among its authors. For example, if a paper has three authors with two authors located in Canada and one in Japan, the modal country for the paper would be Canada. Any ties (i.e., if more than one country is tied for most frequent location among a paper's authors) were broken by randomly selecting among the tied countries.} We can immediately see that the English-language world produces much of the research on social media (which is perhaps unsurprising given that our search term was in English), but that a large amount of research comes from authors in China and Germany.

<<country_table, echo=F, results='asis'>>=
country.table <- sort(table(df[['modal_country']]), decreasing = T, index.return=T )
country.table <- as.data.frame(head(country.table))
colnames(country.table) <- c('Country', 'Number of Papers')
print(xtable(country.table, 
            caption="Top author countries by number of social media papers.",
            align='lp{.5\\linewidth}r', 
			label='tab:country'),
            include.rownames = FALSE)
@

\begin{figure}
    \centering
<<discipline_density, fig.width=8, fig.height=3.5, echo=FALSE, message=FALSE, cached=TRUE>>=

top.subjects <- head(names(rev(sort(table(s$subject)))), 10)
reduced <- full[full$subject %in% top.subjects, c("year", "subject")]
reduced$subject <- droplevels(reduced$subject)

subj.by.year <- melt(table(reduced))
subj.by.year$year <- as.Date(paste(subj.by.year$year, "-06-01", sep=""))
subj.by.year <- subj.by.year[subj.by.year$year <= as.Date("2016-01-01"),]
colnames(subj.by.year) <- c("year", "subject", "papers")
subj.by.year$subject <- as.factor(subj.by.year$subject)

ggplot(subj.by.year) + 
  aes(x=year, y=papers, fill = subject) +
  geom_density(stat="identity", position="stack") + 
  xlab('Year') + ylab('Number of papers') + 
  guides(fill = guide_legend(reverse = TRUE)) +
  # scale_fill_grey(name="Discipline")
  theme_bw()
#$
@
 

\caption{Social media papers published in the top ten disciplines (as categorized by Scopus), over time.}
\label{fig:pubstime}
\end{figure}

Next we look at the disciplines that publish social media research. Figure \ref{fig:pubstime} shows the number of papers containing the term `social media' over time. The plot illustrates that the quantity of published research on social media has increased rapidly over time. The growth appears to slow down more recently, but this may be due to the speed at which the Scopus database imports data about new articles.

Figure \ref{fig:pubstime} shows the top ten disciplines, as categorized by Scopus. We see that the field started off dominated by computer science publications, with additional disciplines increasing their activity in recent years. This story is also reflected in the top venues, listed in Table \ref{tab:source}, where we see that computer science venues have published social media research most frequently.

\begin{table}
  \begin{adjustbox}{center}
<<source_table, echo=F, results='asis'>>=
# Change long titles
df$source_title <- revalue(df$source_title, c('Lecture Notes in Computer Science (including subseries Lecture Notes in Artificial Intelligence and Lecture Notes in Bioinformatics)' = 'Lecture Notes in Computer Science',
'Proceedings of the Annual Hawaii International Conference on System Sciences' = 'Proceedings of the Hawaii International Conference on System Sciences',
'Joint Ninth WebKDD and First SNA-KDD 2007 Workshop on Web Mining and Social Network Analysis' = 'Proceedings of WebKDD / SNA-KDD 2007'))

source.table <- sort(table(df[['source_title']]), decreasing = T, index.return=T )
source.table <- as.data.frame(head(source.table))
colnames(source.table) <- c('Publication Venue', 'Papers')
print(xtable(source.table, 
             align='lp{.8\\linewidth}r'),
      include.rownames = FALSE,
      floating=FALSE)
@
\end{adjustbox}
\caption{Venues with the most social media papers.}
\label{tab:source}
\end{table}

\begin{table}
  \begin{adjustbox}{center}
<<cited_by_table, echo=F, results='asis'>>=
results <- head(df[ order(-df[['cited_by_count']]), ][,c('title','source_title','cited_by_count')])
colnames(results) <- c('Title', 'Publication Venue', 'Cited by')

print(xtable(results,
             align='lp{.48\\linewidth}p{.28\\linewidth}r'),
      include.rownames = FALSE,
      floating=FALSE)
@
  \end{adjustbox}
  \caption{Most cited social media papers.}
  \label{tab:citedby}
\end{table}

We then consider the impact of this set of papers as measured by the citations they have received. Like many phenomena in social systems, citation counts follow a highly skewed distribution with a few papers receiving many citations and most papers receiving very few. Table \ref{tab:citedby} provides a list of the most cited papers. These sorts of distributions suggest the presence of `preferential attachment' \citep{barabasi_emergence_1999} or `Matthew effects' \citep{merton_matthew_1968}, where success leads to greater success.

\subsection{Discussion}

The summary statistics and exploratory visualizations presented above provide an overview of the scope and trajectory of social media research. We find that social media research is growing -- both overall and within many disciplines. We find evidence that computer scientists laid the groundwork for the study of social media, but that social scientists, learning scientists, and medical researchers have increasingly been referring to social media in their published work. We also find several business and marketing papers among the most cited pieces of social media research even though neither these disciplines nor their journals appear among the most prevalent in the dataset.

These results are interesting and believable because they come from a comprehensive database of academic work. In most social science contexts, researchers have to sample from a population and that sampling is often biased. For example, the people willing to come to a lab to participate in a study or take a phone survey may have different attributes from those unwilling to participate. This makes generalizing to the entire population problematic. When using trace data, on the other hand, we often have data from all members of a community including those who would not have chosen to participate. One of the primary benefits of collecting data from a comprehensive resource like Scopus is that it limits the impact of researcher biases or assumptions. For example, we do not have backgrounds in education or medical research; had we tried to summarize the state of social media research by identifying articles and journals manually, we might have overlooked these disciplines.

That said, this apparent benefit can also become a liability when we seek to generalize our results beyond the community that we have data for. The large \textit{N} of big data studies using social media traces may make results appear more valid, precise, or certain, but a biased sample does not become less biased just because it is larger \citep{hargittai_is_2015}. For example, a sample of 100 million Twitter users might be a worse predictor of election results than a truly random sample of only 1,000 likely voters because Twitter users likely have different attributes and opinions than the voting public. Another risk comes from the danger that data providers collect or filter data in ways that aren't apparent. Researchers should think carefully about the relationship of their data to the population they wish to study and find ways to estimate bias empirically.

Overall, we view the ease of obtaining and analyzing digital traces as one of the most exciting developments in social science. Although the hurdles involved represent a real challenge to many scholars of social media today, learning the technical skills required to obtain online trace data is no more challenging than the statistics training that is part of many PhD programs and opens opportunities for important, large-scale studies. Below, we present examples of a few computational analyses that can be done with this sort of data.

\section{Network analysis}

Social network analysis encompasses the most established set of computational methods in the social sciences \citep{wasserman_social_1994}. At its core, network analysis revolves around a `graph' representation of data that tries to capture relationships (called edges) between discrete objects (called nodes). Graphs can represent any type of object and relationship, such as roads connecting a group of cities or shared ingredients across a set of recipes. Graph representations of data, and the network analytic methods built to reason using these data, are widely used across the social sciences as well as other fields including physics, genomics, computer science, and philosophy. `Social network analysis' constitutes a specialized branch of network analysis in which nodes represent people (or other social entities) and edges represent social relationships like friendship, interaction, or communication.

The power of network analysis stems from its capacity to reduce a very large and complex dataset to a relatively simple set of relations that possess enormous explanatory power. For example, \citet{hausmann_atlas_2014} use network data on the presence or absence of trading relationships between countries to build a series of extremely accurate predictions about countries' relative wealth and economic performance over time. By reasoning over a set of relationships in a network, Hausmann and his colleagues show that details of the nature or amount of goods exchanged are not necessary to arrive at accurate economic conclusions.

Network analysis has flourished in studies of citation patterns within scholarly literature, called `bibliometrics' or `scientometrics.' Bibliometric scholars have developed and applied network analytic tools for more than a half-century \citep{kessler_bibliographic_1963, hood_literature_2001}. As a result, bibliometric analysis provides an obvious jumping-off point for our tour of computational methods. Because network methods reflect a whole family of statistics, algorithms, and applications, we focus on approaches that are both well-suited to bibliometric analysis and representative of network analyses used in computational social science more broadly.

\subsection{Our application: Citation networks}

Our network analysis begins by representing citation information we collected from the Scopus APIs as a graph. In our representation, each node represents a paper and each edge represents a citation. Scopus provides data on incoming citations for each article. Our full dataset includes \Sexpr{f(sm.citations)} incoming citations to the \Sexpr{f(total.articles)} articles in Scopus with `social media' in their titles, abstracts, or keywords. \Sexpr{f(total.articles - sm.cited)} of these articles (\Sexpr{round(((total.articles - sm.cited)/total.articles)*100)}\%) have not been cited even once by another article in Scopus and \Sexpr{f(total.articles - sm.citing)} (\Sexpr{round(((total.articles - sm.citing)/total.articles)*100)}\%) do not cite any other article in our sample. The recent development of social media and the rapid growth of the field depicted in Figure \ref{fig:pubstime} might help explain the sparseness (i.e.~lack of connections) of the graph. As a result, and as is often the case in network analysis, a majority of our dataset plays no role in our analysis described in the rest of this section.

Once we create our citation graph, there are many potential ways to analyze it. One important application, common to bibliometrics, is the computational identification of communities or clusters within networks. In network studies, the term `community' is used to refer to groups of nodes that are densely connected to each other but relatively less connected to other groups. In bibliometric analyses, communities can describe fields or sub-fields of articles which cite each other, but are much less likely to cite or be cited by papers in other groups. Although there are many statistical approaches to community detection in network science, we use a technique from Rosvall and Bergstrom (\citeyear{rosvall_maps_2008}) that has been identified as appropriate for the study of bibliometric networks \citep{subelj_clustering_2016}. By looking at the most frequently occurring journals and publication venues in each community, we are able to identify and name sub-fields of social media research as distinct communities.

A citation graph is only one possible network representation of the relationships between articles. For example, the use of common topics or terminology might constitute another type of edge. Alternatively, journals or individual authors (rather than articles) might constitute an alternative source of nodes. In bibliometric analyses, for example, it is common for edges to represent `co-citations' between articles or authors. Using this approach, papers are said to be tied together by a co-citation if they have both been cited in a third document \citep{small_co-citation_1973}. Due to limited space, we only present the simplest case of direct citations.

\begin{figure}
     \includegraphics[width=\textwidth]{figures/g_sm_hairball.pdf}
     \caption{Network visualization of the citation network in our dataset. The layout is `force directed' meaning that nodes (papers) with more edges (citations) appear closer to the center of the figure.}
     \label{fig:hairball}
 \end{figure}

\begin{table}
\begin{adjustbox}{center}
    \begin{tabular}{cm{0.3\textwidth}m{0.5\textwidth}}
         \hline
         Community & Description & Journals \\
         \hline
         \colorbox{CarnationPink}{\color{black}Community 1} & biomedicine; bioinformatics & Journal of Medical Internet Research; PLoS ONE; Studies in Health Technology and Informatics \\
         \colorbox{Green}{\color{black}Community 2} & information technology; management & Computers in Human Behavior; Business Horizons; Journal of Interactive Marketing \\
         \colorbox{Black}{\color{white}Community 3} & communication & Information Communication and Society; New Media and Society; Journal of Communication \\
         \colorbox{Cyan}{\color{black}Community 4} & computer science; network science & Lecture Notes in Computer Science; PLoS ONE; WWW; KDD \\
         \colorbox{Orange}{\color{black}Community 5} & psychology; psychometrics & Computers in Human Behavior; Cyberpsychology, Behavior, and Social Networking; Computers and Education\\
         \colorbox{Red}{\color{black}Community 6} & multimedia & IEEE Transactions on Multimedia; Lecture Notes in Computer Science; ACM Multimedia \\
         \hline
    \end{tabular}
    \end{adjustbox}
    \caption{Description of each of the citation network clusters identified by the community detection algorithm, together with a list of the three most common journals in each community.}
    \label{tab:clusters}
\end{table}

\subsection{Results}

As is common in social networks, the large majority of articles with any citations connect to each other in one large sub-network called a `component'. Figure \ref{fig:hairball} shows a visualization of this large component. The optimal way to represent network data in two-dimensional space is a topic of research and debate. Figure \ref{fig:hairball} uses a force-directed drawing technique \citep{fruchterman_graph_1991}, the most widely used algorithm in network visualization, using the free/open source software package Gephi \citep{bastian_gephi:_2009}. The basic idea behind the algorithm is that nodes naturally push away from each other, but are pulled together by edges between them. Shades in each graph in this section reflect the communities of documents identified by Rosvall and colleagues' `map' algorithm \citep{rosvall_maps_2008, rosvall_map_2010}. Although the algorithm identified several dozen communities, most are extremely small, so we have shown only the largest 6 communities in Figure \ref{fig:hairball}. Each of these communities are summarized in Table \ref{tab:clusters} where the right-most column lists the three most common journals for the articles included in each community.

At this point, we can look in more depth at the attributes of the different communities. For example, in a bibliometric analysis published in the journal \emph{Scientometrics}, \citet{kovacs_exploring_2015} reported summary statistics for articles in each of the major communities identified (e.g., the average number of citations) as well as qualitative descriptions of the nodes in each community. We can see from looking at Table \ref{tab:clusters} that the communities point to the existence of coherent thematic groups. For example, \colorbox{CarnationPink}{\color{black}Community 1} includes biomedical research while \colorbox{black}{\color{white}Community 3} contains papers published in communication journals. Earlier, we relied on an existing category scheme applied to journals to create Figure \ref{fig:pubstime}; all articles published in particular journals were treated as being within one field. Network analysis, however, can identify groups and categories of articles in terms of who is citing whom and, as a result, can reveal groups that cross journal boundaries. PLoS ONE, for example, is a `megajournal' that publishes articles from all scientific fields \citep{binfield_plos_2012}. As a result, PLoS ONE is one of the most frequently included journals in both \colorbox{CarnationPink}{\color{black}Community 1} and \colorbox{Red}{\color{black}Community 6}. In a journal-based categorization system, articles may be misclassified or not classified at all.

\begin{figure}
    \centering
    \includegraphics[width=0.4\textwidth]{figures/cluster_connections.pdf}
    \caption{Graphical representation of citations between communities using the same grayscale mapping described in Table \ref{tab:clusters}. The size of the nodes reflects the total number of papers in each community. The thickness of each edge reflects the number of outgoing citations. Edges are directional, and share the color of their source (i.e., citing) community.}
    \label{fig:cluscon}
\end{figure}

Network analysis can also reveal details about the connections between fields. Figure \ref{fig:cluscon} shows a second network we have created in which our communities are represented as nodes and citations from articles in one community to articles in the other communities are represented as edges. The thickness of each edge represents the number of citations and the graph shows the directional strength of the relative connections between communities. For example, the graph suggests that the communication studies community (\colorbox{Black}{\color{white}Community 3}) cites many papers in information technology and management (\colorbox{Green}{\color{black}Community 2}) but that this relationship is not reciprocated.

\subsection{Discussion}

Like many computational methods, the power of network techniques comes from the representation of complex relationships in simplified forms. Although elegant and powerful, the network analysis approach is inherently reductive in nature and limited in many ways. What we gain in our ability to analyze millions or billions of individuals comes at the cost of speaking about particular individuals and sub-groups. A second limitation stems from the huge number of relationships that can be represented in graphs. A citation network and a co-citation network, for example, represent different types of connections and these differences might lead an algorithm to identify different communities. As a result, choices about the way that edges and nodes are defined can lead to very different conclusions about the structure of a network or the influence of particular nodes. Network analyses often treat all connections and all nodes as similar in ways that mask important variation.

Network analysis is built on the assumption that knowing about the relationships between individuals in a system is often as important, and sometimes more important, than knowing about the individuals themselves. It inherently recognizes interdependence and the importance of social structures. This perspective comes with a cost, however. The relational structure and interdependence of social networks make it impossible to use traditional statistical methods and SNA practitioners have had to move to more complex modeling strategies and simulations to test hypotheses.

\section{Text analysis}

Social media produces an incredible amount of text, and social media researchers often analyze the content of this text. For example, researchers use ethnographic approaches \citep{kozinets_field_2002} or content analysis \citep{chew_pandemics_2010} to study the texts of interactions online. Because the amount of text available for analysis is far beyond the ability of any set of researchers to analyze by hand, scholars increasingly turn to computational approaches. Some of these analyses are fairly simple, such as tracking the occurrence of terms related to a topic or psychological construct \citep{tausczik_psychological_2010}. Others are more complicated, using tools from natural language processing (NLP). NLP includes a range of approaches in which algorithms are applied to texts, such as machine translation, optical character recognition, and part-of-speech tagging. Perhaps the most common use in the social sciences is sentiment analysis, in which the affect of a piece of text is intuited based on the words that are used \citep{asur_predicting_2010}. Many of these techniques have applications for social media research.

One natural language processing technique -- topic modeling -- is used increasingly frequently in computational social science research. Topic modeling seeks to identify topics automatically within a set of documents. In this sense, topic modeling is analogous to content analysis or other manual forms of document coding and labeling. However, topic models are a completely automated, unsupervised computational method -- i.e., topic modeling algorithms do not require any sort of human intervention, such as hand-coded training data or dictionaries of terms. Topic modeling scales well to even very large datasets, and is most usefully applied to large corpora of text where labor-intensive methods like manual coding are simply not an option.

When using the technique, a researcher begins by feeding topic modeling software the texts that she would like to find topics for and by specifying the number of topics to be returned. There are multiple algorithms for identifying topics, but we focus on the most common: \emph{latent Dirichlet allocation} or LDA \citep{blei_latent_2003}. The nuts and bolts of how LDA works are complex and beyond the scope of this chapter, but the basic goal is fairly simple: LDA identifies sets of words that are likely to be used together and calls these sets `topics.' For example, a computer science paper is likely to use words like `algorithm', `memory', and `network.' While a communication article might also use `network,' it would be much less likely to use `algorithm' and more likely to use words like `media' and `influence.' The other key feature of LDA is that it does not treat documents as belonging to only one topic, but as consisting of a mixture of multiple topics with different degrees of emphasis. For example, an LDA analysis might characterize this chapter as a mixture of computer science and communication (among other topics). 

LDA identifies topics inductively from the observed distributions of words in documents. The LDA algorithm looks at all of the words that co-occur within a corpus of documents and assumes that words used in the same document are more likely to be from the same topic. The algorithm then looks across all of the documents and finds the set of topics and topic distributions that would be, in a statistical sense, most likely to produce the observed documents. LDA's output is the set of topics: ranked lists of words likely to be used in documents about each topic, as well as the distribution of topics in each document. \citet{dimaggio_exploiting_2013} argue that while many aspects of topic modeling are simplistic, many of the assumptions have parallels in sociological and communication theory. Perhaps more importantly, the topics created by LDA frequently correspond to human intuition about how documents should be grouped or classified.

The results of topic models can be used many ways. Our dataset includes \Sexpr{nrow(abstracts[grep('LDA',abstracts[['abstract']]),])} publications with the term `LDA' in their abstracts. Some of these papers use topic models to conduct large-scale content analysis, such as looking at the topics used around health on Twitter \citep{prier_identifying_2011,ghosh_what_2013}. Researchers commonly use topic modeling for prediction and machine learning tasks, such as identifying how topics vary by demographic characteristics and personality types \citep{schwartz_personality_2013}. In our dataset, papers use LDA to predict transitions between topics \citep{wang_tm-lda:_2012}, to recommend friends based on similar topic use \citep{pennacchiotti_investigating_2011}, and to identify interesting tweets on Twitter \citep{yang_identifying_2014}.


\subsection{Our application: Identifying topics in social media research}

We apply LDA to the texts of abstracts in our dataset in order to identify prevalent topics in social media research. We show how topics are extracted and labeled and then use data on topic distributions to show how the focus of social media research has changed over time. We begin by collecting each of the abstracts for the papers in our sample. Scopus does not include abstract text for \Sexpr{f(total.articles - nrow(abstracts))} of the \Sexpr{f(total.articles)} articles in our sample. We examined a random sample of the entries with missing abstracts by hand, and found that abstracts for many simply never existed (e.g., articles published in trade journals or books). Other articles had published abstracts, but the text of these abstracts, for reasons that are not clear, were not available through Scopus.\footnote{This provides one example of how the details of missing data can be invisible or opaque. It is easy to see how missing data like this could impact research results. For example, if certain disciplines or topics are systematically less likely to include abstracts in Scopus, we will have a skewed representation of the field.}
We proceed with the \Sexpr{f(nrow(abstracts))} articles in our sample for which abstract data was available.
The average abstract in this dataset is \Sexpr{f(round(mean(word_count),2))} words long, with a max of \Sexpr{f(max(word_count))} words and a minimum of \Sexpr{f(min(word_count))} (``\Sexpr{abstracts[which.min(word_count),'abstract']}'').

We then remove `stop words' (common words like `the,'`of,' etc.) and tokenize the documents by breaking them into unigrams and bigrams (one-word and two-word terms). We analyze the data using the Python \emph{LatentDirichletAllocation} module from the \emph{scikit-learn} library \citep{pedregosa_scikit-learn:_2011}. Choosing the appropriate number of topics to be returned (typically referred to as \textit{k}) is a matter of some debate and research \citep[e.g.,][]{arun_finding_2010}. After experimenting with different values of \textit{k}, plotting the distribution of topics each time in a way similar to graph shown in Figure \ref{fig:ldaplots}, we ultimately set \textit{k} as twelve. At higher values of \textit{k}, additional topics only rarely appeared in the abstracts.

\subsection{Results}

Table \ref{topic_table} shows the top words for each of the topics discovered by the LDA model, sorted by how common each topic is in our dataset.
At this point, researchers typically evaluate the lists of words for coherence and give names to each of the topics. For example, we look at the words associated with Topic 1 and give it the name `Media Use.' Of course, many other names for this topic could be chosen. We might call it `Facebook research' because it is the only topic which includes the term `facebook.' Researchers often validate these names by looking at some of the texts which score highest for each topic and subjectively evaluating the appropriateness of the chosen name as a label for those texts. For example, we examined the abstracts of the five papers with the highest value for the `Media Use' topic and confirmed that we were comfortable claiming that they were examples of research about media use. In this way, topic modeling requires a mixture of both quantitative and qualitative interpretation. The computer provides results, but making sense of those results requires familiarty with the data.

\begin{table}
  \tiny
  \begin{adjustbox}{center}
    \input{tables/topic_words1.tex}
  \end{adjustbox}
  
  \vspace{1em}
  
  \begin{adjustbox}{center}
    \input{tables/topic_words2.tex}
  \end{adjustbox}
    \caption{Top 20 terms for each topic. Topics are presented in the order of their frequency in the corpus of abstracts.}
\label{topic_table}
\end{table}


\begin{figure}
\centering
<<lda_visualizations, echo=FALSE, message=FALSE, fig.width=7.5, fig.height=5.2, out.width='\\textwidth', dev='pdf'>>=
data.sets <- c("topic.sums", "topic.means", "weighted.sums")

tmp <- lapply(data.sets, function (x) {
    d <- eval(as.name(x))
    d$year <- rownames(d)
    d <- melt(d, id.vars="year")
    colnames(d) <- c("year", "Category", "value")
    d[["variable"]] <- x
    d
})

grid.tmp <- do.call("rbind", tmp)

grid.tmp$Category <- gsub("\\." , " ", grid.tmp$Category)
grid.tmp$Category <- factor(grid.tmp$Category, levels=unique(grid.tmp$Category))

grid.tmp$year <- as.Date(paste(grid.tmp$year, "-07-21", sep=""))

grid.tmp$variable <- revalue(grid.tmp$variable, c("weighted.sums"="Weighted Sums", "topic.sums"="Topic Sums", "topic.means"="Topic Means"))
grid.tmp$variable <- factor(grid.tmp$variable, levels=c("Topic Sums", "Topic Means", "Weighted Sums"))

# drop 2016
grid.tmp <- grid.tmp[grid.tmp$year <= as.Date("2015-01-01"),]

ggplot(grid.tmp) + aes(x=year, y=value, group=Category,
                       color=Category
                       ) + geom_line(aes(linetype=Category)) +
    facet_grid(variable ~ ., scale="free_y") +
    labs(x="Year", y="") + # scale_colour_grey() +
    theme_bw()
#$
@
\caption{Statistics from our LDA analysis, over time. The top panel shows topic sums which capture the amount that each topic is used in abstracts, by year. The middle panel shows topic means which are the average amount that each topic is used in a given abstract. The bottom panel shows the amount that each topic is used in abstracts, by year, weighted by citation count.}
\label{fig:ldaplots}
\end{figure}

The top panel of Figure \ref{fig:ldaplots} shows how the distribution of topics identified by LDA in our analysis has changed over time. The LDA algorithm gives each abstract a probability distribution over each of the topics, such that it sums to 1 (e.g., a given abstract may be 80\% `Social Network Analysis,' 20\% `Education,' and 0\% everything else). To construct Figure \ref{fig:ldaplots}, we sum these percentages for all of the documents published in each year and plot the resulting prevalence of each topic over time.\footnote{More complex approaches such as dynamic LDA \citep{blei_dynamic_2006} are often better suited to identify the temporal evolution of topics.}

The figures provide insight into the history and trajectory of social media research. Looking at the top figure, it appears that the `Social Network Analysis' topic was the early leader in publishing on social media, but was overtaken by the `Media Use' topic around 2012. This pattern is even more apparent when we look at the mean amount that each topic was used each year (the middle panel of Figure \ref{fig:ldaplots}). In the bottom panel, we take a third look at this data by weighting the topics used in each paper by the log of the number of citations that the paper received. This final statistic characterizes how influential each topic has been. The overall story is similar, although we see that the `Health' topic and the `Media Use' topic are more influential than the non-weighted figures suggest.

\subsection{Discussion}

Some of the strengths of topic modeling become apparent when we compare these LDA-based analyses with the distribution of papers by discipline that we created earlier (Figure \ref{fig:pubstime}). In this earlier attempt, we relied on the categories that Scopus provided and found that early interest in social media was driven by computer science and information systems researchers. Through topic modeling, we learn that these researchers engaged in social network analysis (rather than interface design, for example). While some of our topics match up well with the disciplines identified by Scopus, a few are more broad (e.g., `Media Use') and most are more narrow (e.g., `Sentiment Analysis'). This analysis might provide a richer sense of the topics of interest to social media researchers. Finally, these topics emerged inductively without any need for explicit coding, such as classifying journals into disciplines. This final feature is a major benefit in social media research where text is rarely categorized for researchers ahead of time.

Topic modeling provides an intuitive, approachable way of doing large-scale text analysis. Its outputs can be understandable and theory-generating. The inductive creation of topics has advantages over traditional content analysis or `supervised' computational methods that require researchers to define labels or categories of interest ahead of time. While the results of topic models clearly lack the nuance and depth of understanding that human coders bring to texts, the method allows researchers to analyze datasets at a scale and granularity that would take a huge amount of resources to code manually.

There are, of course, limitations to topic modeling. Many of LDA's limitations have analogues in manual coding. One we have already mentioned is that researchers must choose the number of topics without any clear rules about how to do so. A similar problem exists in content analysis, but the merging and splitting of topics can be done more intuitively and intentionally.
An additional limitation is that topic modeling tends to work best with many long documents. This can represent a stumbling block for researchers with datasets of short social media posts or comments; in these cases posts can be aggregated by user or by page to produce meaningful topics. The scope of documents can also affect the results of topic models. If, in addition to using abstracts about `social media,' we had also included abstracts containing the term `gene splicing,' our twelve topics would be divided between the two fields and each topic would be less granular. To recover topics similar to those we report here, we would have to increase the number of topics created.

As with network analysis, a goal of LDA is to distill large, messy, and noisy data down to much simpler representations in order to find patterns. Such simplification will always entail ignoring some part of what is going on. Luckily, human coders and LDA have complementary advantages and disadvantages in this regard. Computational methods do not understand which text is more or less important. Humans are good at seeing the meaning and importance of topics, but may suffer from cognitive biases and miss out on topics that are less salient \citep{dimaggio_exploiting_2013}. Topic models work best when they are interpreted by researchers with a rich understanding of the texts and contexts under investigation.

\section{Predicting citation}

A final computational technique is statistical prediction. Statistical prediction can come in handy in situations where researchers have a great deal of data, including measures of an important, well-defined outcome they care about, but little in the way of prior literature or theory to guide analysis. Prediction has become a mainstream computational approach that encompasses a number of specific statistical techniques including classification, cross validation, and machine learning (also known as statistical learning) methods \citep{tibshirani_regression_1996}. Arguably made most famous by Nate \citet{silver_signal_2015}, who uses the technique to predict elections and sporting event outcomes, prediction increasingly colors public discourse about current events \citep{domingos_master_2015}.

There are many approaches to prediction. We focus on regression-based prediction because it offers a reasonably straightforward workflow. Begin by breaking a dataset into two random subsets: a large subset used as `training' data and a small subset as `holdout' or `test' data. Next, use the training data to construct a regression model of a given outcome (dependent variable) that incorporates a set of features (independent variables) that might explain variations in the outcome. Apply statistical model selection techniques to determine the best weights (coefficients) to apply to the variables. Evaluate the performance of the model by seeing how accurately it can predict the outcome on the test data. After selecting an appropriate model, assess and interpret the items that most strongly predict the outcome. One can even compare the performance of different or nested sets of features by repeating these steps with multiple groups of independent variables.

Interpreting the results of statistical prediction can be less clear-cut. The term `prediction' suggests a deep knowledge of a complex social process and the factors that determine a particular outcome. However, statistical prediction often proves more suitable for exploratory analysis where causal mechanisms and processes are poorly understood. We demonstrate this in the following example that predicts whether or not papers in our dataset get cited during the period of data collection. In particular, we try to find out whether textual features of the abstracts can help explain citation outcomes. Our approach follows that used by \citet{mitra_language_2014}, who sought to understand what textual features of Kickstarter projects predicted whether or not projects were funded.

\subsection{Our application: Predicting paper citation}

<<attach_citation_descrip, echo=FALSE, message=FALSE>>=
attach(pred.descrip)
@

We use multiple attributes of the papers in our dataset, including text of their abstracts, to predict citations. About \Sexpr{f(round(table(cited)[["TRUE"]] / total.articles * 100, 0))}\% of the papers (\Sexpr{f(length(cited[cited]))} out of \Sexpr{f(total.articles)}) received one or more citations ($\mu = \Sexpr{f(round(mean(cites),2))}$; $\sigma = \Sexpr{f(round(sd(cites), 2))}$). Can textual features of the abstracts explain which papers receive citations? What about other attributes, such as the publication venue or subject area? A prediction analysis can help evaluate these competing alternatives.

To begin, we generate a large set of features for each paper from the Scopus data. Our measures include the year, month, and language of publication as well as the number of citations each paper contains to prior work. We also include the modal country of origin of the authors as well as the affiliation of the first author. Finally, we include the publication venue and publication subject as provided by Scopus. Then, we build the textual features by taking all of the abstracts and moving them through the following sequence of steps similar to those we took when performing LDA: we lowercase all the words; remove all stop words; and create uni-, bi-, and tri-grams. 

We also apply some inclusion criteria to both papers and features. To avoid subject-specific jargon, we draw features only from those terms that appear across at least 30 different subject areas. To avoid spurious results, we also exclude papers that fall into unique categories. For example, we require that there be more than one paper published in any language, journal, or subject area that we include as a feature. These sorts of unique cases can cause problems in the context of prediction tasks because they may predict certain outcomes perfectly. As a result, it is often better to focus on datasets and measures that are less `sparse' (i.e.,~characterized by rare, one-off observations). Once we drop the \Sexpr{ f( length(cited) - length(covars['cited']))} papers that do not meet these criteria, we are left with \Sexpr{f(length(covars['cited']))} papers. 

We predict the dichotomous outcome variable \emph{cited}, which indicates whether a paper received any citations during the period covered by our dataset (2004-2016). We use a method of \emph{penalized logistic regression} called the least absolute shrinkage and selection operator (also known as the \emph{Lasso}) to do the prediction work. Although, the technical details of Lasso models lie beyond the scope of this chapter, it, and other penalized regression models, work well on data where many of the variables have nearly identical values (sometimes called collinear variables because they would sit right around the same line if you plotted them) and/or many zero values (this is also called `sparse' data) \citep{friedman_regularization_2010, james_introduction_2013}. In both of these situations, some measures are redundant; the Lasso uses clever math to pick which of those measures should go into your final model and which ones should be, in effect, left out.\footnote{To put things a little more technically, a fitted Lasso model \emph{selects} the optimal set of variables that should have coefficient values greater than zero and \emph{shrinks} the rest of the coefficients to zero without sacrificing goodness of fit \citep{tibshirani_regression_1996}.} The results of a Lasso model are thus more computationally tractable and easier to interpret. 

We use a common statistical technique called cross-validation to validate our models. Cross-validation helps solve another statistical problem that can undermine the results of predictive analysis. Imagine fitting an ordinary least squares regression model on a dataset to generate a set of parameter estimates reflecting the relationships between a set of independent variables and some outcome. The model results provide a set of weights (the coefficients) that represent the strength of the relationships between each predictor and the outcome. Because of the way regression works (and because this is a hypothetical example and we can assume data that does not violate the assumptions of our model), the model weights are the best, linear, unbiased estimators of those relationships. In other words, the regression model fits the data as well as possible. However, nothing about fitting this one model ensures that the same regression weights will provide the best fit for some new data from the same population that the model has not seen. A model may be overfit if it excellently predicts the dataset it was fitted on but poorly predicts new data. Overfitting in this way is a common concern in statistical prediction. Cross-validation addresses this overfitting problem. First, the training data is split into equal-sized groups (typically 10). Different model specifications are tested by iteratively training them on all but one of the groups, and testing how well they predict the final group. The specification that has the lowest average error is then used on the full training data to estimate coefficients.\footnote{For our Lasso models, cross-validation was used to select $\lambda$, a parameter that tells the model how quickly to shrink variable coefficients. We include this information for those of you who want to try this on your own or figure out the details of our statistical code.} This approach ensures that the resulting models not only fit the data that we have, but that they are likely to predict the outcomes for new, unobserved results. For each model, we report the mean error rate from the cross-validation run which produced the best fit. 

Our analysis proceeds in multiple stages corresponding to the different types of measures we use to predict citation outcomes. We start by estimating a model that includes only the features that correspond to paper and author-level attributes (year, month, and language of publication, modal author country). We then add information about the first author's affiliation. Next, we include predictors that have more to do with research topic and field-level variations (publication venue and subject area). Finally, we include the textual features (terms) from the abstracts.

\subsection{Results}

Table \ref{tab:predict_models} summarizes the results of our prediction models. We include goodness-of-fit statistics and prediction error rates for each model as we add more features. A `better' model will fit the data more closely (i.e.,~it will explain a larger percentage of the deviance) and produce a lower error rate. We also include a supplementary error rate calculated against the `held-back' data, created from a random subset of 10\% of the original dataset that was not used in any of our models. An intuitive way to think about the error rate is to imagine it as the percentage of unobserved papers for which the model will correctly predict whether or not it receives any citations. The two error rate statistics are just this same percentage calculated on different sets of unobserved papers. Unlike a normal regression analysis, we do not report or interpret the full battery of coefficients, standard errors, t-statistics, or p-values. In part, we do not report this information because the results of these models are unwieldy -- each model has over 2,000 predictors and most of those predictors have coefficients of zero! Additionally, unlike traditional regression results, coefficient interpretation and null hypothesis testing with predictive models remain challenging (for reasons that lie beyond the scope of this chapter). Instead, we focus on interpreting the relative performance of each set of features. After we have done this, we refer to the largest coefficients to help add nuance to our interpretation.\\

\begin{table}
\begin{adjustbox}{center}
<<predict_table, echo=FALSE, message=FALSE, results='asis'>>=
detach(pred.descrip)
attach(predict.list)

print(xtable(results.tab,
             align='llrrrr'),
      include.rownames=FALSE,
      floating=FALSE)
@
\end{adjustbox}

\caption{Summary of fitted models predicting citation. The `Model' column describes which features were included. The N features column shows the number of features included in the prediction. `Deviance' summarizes the goodness of fit as a percentage of the total deviance accounted for by the model. `CV error' (cross-validation error) reports the prediction error rates of each model in the cross-validation procedure conducted as part of the parameter estimation process. `Holdout error' shows the prediction error on a random 10\% subset of the original dataset not included in any of the model estimation procedures.}
\label{tab:predict_models}
\end{table}

The results reveal that all of the features improve the goodness of fit, but not necessarily the predictive performance of the models. As a baseline, our controls-only model has a \Sexpr{f(as.numeric(as.character(results.tab[1,5])))}\% classification error on the holdout sample. This level of precision barely improves with the addition of both the author affiliation and subject area features. We observe substantial improvements in the prediction performance when the models include the publication venue features and the abstract text terms. When it comes to research about social media, it appears that venue and textual content are the most informative features for predicting whether or not articles get cited.

To understand these results more deeply, we explore the non-zero coefficient estimates for the best-fitting iteration of the full model. Recall that the Lasso estimation procedure returns coefficients for a subset of the parameters that produce the best fit and shrinks the other coefficients to zero. While it does not make sense to interpret the coefficients in the same way as traditional regression, the non-zero coefficients indicate what features the model identified as the most important predictors of the outcome. First, we note that among the \Sexpr{f(nrow(nz.coefs))} features with non-zero coefficients, only \Sexpr{f(sum(round(prop.table(table(nz.coefs['Type']))*100, 2)[c("country", "language", "month", "year")]))}\% are control measures (country, language, month, and year of publication). Similarly, \Sexpr{f(round(prop.table(table(nz.coefs$Type))*100,2)["subject"])}\% are subject features. In contrast, \Sexpr{f(round(prop.table(table(nz.coefs$Type))*100, 2)["affiliation"])}\% are affiliation features, \Sexpr{f(round(prop.table(table(nz.coefs$Type))*100, 2)["venue"])}\% are venue features, and a whopping \Sexpr{f(round(prop.table(table(nz.coefs$Type))*100, 2)["term"])}\% are textual terms. Once again, we find that publication venue and textual terms do the most to explain which works receive citations. 

Closer scrutiny of the features with the largest coefficients adds further nuance to this interpretation. Table \ref{tab:nzcoefs} shows the ten features with the largest coefficients in terms of absolute value. The Lasso model identified these coefficients as the most informative predictors of whether or not papers in our dataset get cited. Here we see that the majority of these most predictive features are publication venues. The pattern holds across the 100 features with the largest coefficients, of which \Sexpr{f(round(prop.table(table(nz.coefs$Type[1:100]))*100, 2)["venue"])} are publication venues and only \Sexpr{f(round(prop.table(table(nz.coefs$Type[1:100]))*100, 2)["term"])} are textual terms from the abstracts. In other words, variations in publication venue predict which work gets cited more than any other type of feature.

\begin{table}
  \begin{adjustbox}{center}
<<prediction_coefs_tab, echo=FALSE, message=FALSE, results='asis'>>=
print(xtable(as.matrix(head(nz.coefs, 10)),
             align='lllr'
             ),
      include.rownames=FALSE,
      floating=FALSE)
@
\end{adjustbox}
\caption{Feature, variable type, and beta value for top 10 non-zero coefficients estimated by the best fitting model with all features included. Note that the outcome is coded such that positive coefficients indicate features that positively predict the observed outcome of interest (getting cited) while negative coefficients indicate features that negatively predict the outcome.}
\label{tab:nzcoefs}
\end{table}
    
\subsection{Discussion}

The results of our prediction models suggest that two types of features -- publication venue and textual terms -- do the most to explain whether or not papers on social media get cited. Both types of features substantially improve model fit and reduce predictive error in ten-fold cross-validation as well as on a holdout 10\% sub-sample of the original dataset. However, the venue features appear to have a much stronger relationship to our outcome (citation), with the vast majority of the most influential features in the model coming from the venue data  (\Sexpr{f(round(prop.table(table(nz.coefs$Type[1:100]))*100, 2)["venue"])} of the 100 largest coefficients).

As we said at the outset of this section, statistical prediction offers an exploratory, data-driven, and inductive approach. Based on these findings, we conclude that the venue where research on social media gets published better predicts whether that work gets cited than the other features in our dataset. Textual terms used in abstracts help to explain citation outcomes across the dataset, but the relationship between textual terms and citation only becomes salient in aggregate. On their own, hardly any of the textual terms approach the predictive power of the venue features. Features such as author affiliation and paper-level features like language or authors' country provide less explanatory power overall.

The approach has several important limitations. Most important, statistical prediction only generates `predictions' in a fairly narrow, statistical sense. Language of prediction often sounds like the language of causality and inferring process, but these methods do not guarantee that anything being studied is causal or explanatory in terms of mechanisms. We do not claim that a paper's publication venue or the phrases in its abstract \emph{cause} people to cite it. Rather, we think these attributes of a paper likely index specific qualities of an article that are linked to citation outcomes. Just because something is predictive does not mean it is deterministic or causal. 
We also note that the sort of machine learning approach we demonstrate here does not support the types of inferences commonly made with frequentist null hypothesis tests (the sort that lead to p-values and stars next to `significant' variables in a regression model). Instead, the interpretation of learning models rests on looking closely at model summary statistics, objective performance metrics (such as error rates), and qualitative exploration of model results.

\section{Conclusion}

In this chapter, we have described computational social scientific analysis of social media by walking through a series of example analyses. We began with the process of collecting a dataset of bibliographic information on social media scholarship using a web API similar to those provided by most social media platforms. We then subjected this dataset to three of the mostly widely used computational techniques: network analysis, topic modeling, and statistical prediction. Most empirical studies would employ a single, theoretically-motivated analytic approach, but we compromised depth in order to illustrate the diversity of computational research methodologies available. As we have shown, each approach has distinct strengths and limitations.

We believe our examples paint a realistic picture of what is involved in typical computational social media research. However, these analyses remain limited in scope and idiosyncratic in nature. For example, there are popular computational methods we did not cover in this chapter. Obvious omissions include other forms of machine learning, such as decision trees and collaborative filtering \citep{resnick_grouplens:_1994}, as well as simulation-based techniques such as agent-based modeling \citep{macy_factors_2002, wilensky_introduction_2015}.

Despite our diffuse approach, we report interesting substantive findings about the history and state of social media research. We discovered a number of diverse communities studying social media. We used different tools to identify these communities, including the categories provided by Scopus, the results of a community detection algorithm applied to the citation network, and the topics identified by topic modeling. Each analysis provided a slightly different picture of social media research. We learned that the study of social media related to media use and medical research is on the rise. We also learned that social network research was influential at the early stages of social media research, but that it is not as influential in the citation network. All of these findings are complicated by our final finding that subject area is not as good a predictor of whether a paper will receive a citation as the publication venue and the terms used in the abstract.

In the process of describing our analyses, we tried to point to many of the limitations of computational research methods.
Although computational methods and the promise of `big data' elicit excitement, this hype can obscure the fact that large datasets and fast computers do nothing to obviate the fundamentals of high quality social science: researchers must understand their empirical settings, design studies with care, operationalize concepts in ways that are valid and honest, take steps to ensure that their findings generalize, and ask tough questions about the substantive impacts of observed relationships. These tenets extend to computational research as well.

Other challenges go beyond methodological limitations. Researchers working with passively collected data generated by social media can face complex issues around the ethics of privacy and consent as well as the technical and legal restrictions on automated data collection. Computational analyses of social media often involve datasets gathered without the sort of active consent considered standard in other arenas of social scientific inquiry. In some cases, data is not public and researchers access it through private agreements (or employment arrangements) with companies that own platforms or proprietary databases. In others, researchers obtain social media data from public or semi-public sources, but the individuals creating the data may not consider their words or actions public and may not even be aware that their participation generates durable digital traces \citep{boyd_critical_2012}. A number of studies have been criticized for releasing information that researchers considered public, but which users did not \citep{zimmer_okcupid_2016}. In other cases, researchers pursuing legitimate social inquiry have become the target of companies or state prosecutors who selectively seek to enforce terms of service agreements or invoke broad laws such as the federal Computer Fraud and Abuse Act (CFAA).\footnote{See \citepos{sandvig_why_2016} blogpost, ``Why I am Suing the Government,'' for a thoughtful argument against the incredibly vague and broad scope of the CFAA as well as a cautionary tale for those who write software to conduct bulk downloads of public website data for research purposes.}

We advise computational researchers to take a cautious and adaptive approach to these issues. Existing mechanisms such as Institutional Review Boards and federal laws have been slow to adjust to the realities of online research. In many cases, the authority and resources to anticipate, monitor, or police irresponsible behaviors threaten to impose unduly cumbersome restrictions. In other cases, review boards' policies greenlight research that seems deeply problematic. We believe researchers must think carefully about the specific implications of releasing specific datasets. In particular, we encourage abundant caution and public consultation before disseminating anything resembling personal information about individual social media system users. Irresponsible scholarship harms both subjects and reviewers and undermines the public trust scholars need to pursue their work.

At the same time, we remain excited and optimistic about the future of computational studies of social media. As we have shown, the potential benefits of computational methods are numerous. Trace data can capture behaviors that are often difficult to observe in labs and that went unrecorded in offline interactions. Large datasets allow researchers to measure real effects obscured by large amounts of variation, and to make excellent predictions using relatively simple models. These new tools and new datasets provide a real opportunity to advance our understanding of the world. Such opportunities should not be undermined by overly-broad laws or alarmist concerns.

Finally, much of computational social science, including this chapter, is data-focused rather than theory-focused. We would encourage others to do as we say, and not as we do. The great promise of computational social science is the opportunity to test and advance social science theory. We hope that readers of this chapter will think about whether there are theories they are interested in which might benefit from a computational approach. We urge readers with a stronger background in theory to consider learning the tools to conduct these types of analyses and to collaborate with technically minded colleagues.

\subsection{Reproducible research}

Computational research methods also have the important benefit of being extraordinarily reproducible and replicable \citep{stodden_toward_2013}. Unlike many other forms of social research, a computational researcher can theoretically use web APIs to collect a dataset identical to one used in a previous study.
Even when API limits or other factors prohibit creating an identical dataset, researchers can work to make data available alongside the code they use for their analysis, allowing others to re-run the study and assess the results directly. 
Making code and data available also means that others can analyze and critique it. This can create uncomfortable situations, but we feel that such situations serve the long-term interests of society and scholarly integrity. Although not every computational researcher shares their code \citep{stodden_toward_2013} there are movements to encourage or require this \citep{leveque_reproducible_2012, stodden_toward_2013, bollen_social_2015}. 

We have tried to follow emerging best practices with regards to reproducibility in this chapter. We have released an online copy of all of the code that we used to create this chapter. By making our code available, we hope to make our unstated assumptions and decisions visible. By looking at our code, you might find errors or omissions which can be corrected in subsequent work. By releasing our code and data, we also hope that others can learn from and build on our work. 
For example, a reader with access to a server and some knowledge of the Python and R programming languages should be able to build a more up-to-date version of our dataset years from now. Another reader might create a similar bibliographic analysis of another field. By using our code, this reader should able to produce results, tables, and figures like those in this chapter. Data repositories, such as the Harvard Dataverse, make storing and sharing data simple and inexpensive.
When thinking of the opportunities for openness, transparency, and collaboration, we are inspired by the potential of computational research methods for social media. We hope that our overview, data, and code can facilitate more of this type of work.

\section{Online supplements}
\label{sec-supp}

All of the code used to generate our dataset, to complete our analyses, and even to produce the text of this chapter, is available for download on the following public website: \url{https://communitydata.cc/social-media-chapter/}

Because the Scopus dataset is constantly being updated and changed, reproducing the precise numbers and graphs in this chapter requires access to a copy of the dataset we collected from Scopus in 2016. Unfortunately, like many social media websites, the terms of use for the Scopus APIs prohibit the re-publication of data collected from their database. However, they did allow us to create a private, access-controlled, replication dataset in the Harvard Dataverse archive at the following URL: \url{http://dx.doi.org/10.7910/DVN/W31PH5}. Upon request, we will grant access to this dataset to any researchers interested in reproducing our analyses.

% bibliography here
\printbibliography[title = {References}, heading=secbib]

\end{document}

%  LocalWords:  Foote BrickRed lazer Scopus wasserman blei james neef
%  LocalWords:  geo howison flossmole leskovec programmatically JSON
%  LocalWords:  NodeXL hansen droplevels sep ggplot aes xlab ylab bw
%  LocalWords:  df cbind xtable lp linewidth Weibo eigenvector welles
%  LocalWords:  hausmann bibliometrics scientometrics kessler sm ccm
%  LocalWords:  rosvall subelj subfields biomedicine tm dplyr plyr nz
%  LocalWords:  bioinformatics Informatics KDD psychometrics Gephi sd
%  LocalWords:  Cyberpsychology fruchterman bastian gephi kovacs plos
%  LocalWords:  megajournal binfield kozinets tausczik asur LDA ghosh
%  LocalWords:  dimaggio relationality heteroglossia copresence LIWC
%  LocalWords:  schwartz regressors olds wang lda pennacchiotti pdf
%  LocalWords:  facebook textwidth tmp lapply eval rbind gsub mitra
%  LocalWords:  Kickstarter tri collinear stodden leveque bollen SNA
%  LocalWords:  secbib textbf textcolor wrapify formatC WebKDD merton
%  LocalWords:  citedby barabasi matthew hargittai Bergstrom snagrey
%  LocalWords:  misclassified grayscale tokenize unigrams bigrams
%  LocalWords:  LatentDirichletAllocation scikit linetype colour pred
%  LocalWords:  dimensionality tibshirani domingos descrip covars
%  LocalWords:  friedman llrrrr coefs nzcoefs lllr macy LDA's
%  LocalWords:  frequentist resnick grouplens wilensky boyd zimmer
%  LocalWords:  okcupid CFAA Sandvig's blogpost replicable Dataverse
%  LocalWords:  reproducibility greenlight
