<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ben Roston on Medium]]></title>
        <description><![CDATA[Stories by Ben Roston on Medium]]></description>
        <link>https://medium.com/@ben.roston?source=rss-43d56b97a3c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*15OQOF306RXFKmRGoJ725g.jpeg</url>
            <title>Stories by Ben Roston on Medium</title>
            <link>https://medium.com/@ben.roston?source=rss-43d56b97a3c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:32:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ben.roston/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An Introduction to Equity and Justice: A Video Game Perspective]]></title>
            <link>https://medium.com/@ben.roston/an-introduction-to-equity-and-justice-a-video-game-perspective-b4d919f08134?source=rss-43d56b97a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4d919f08134</guid>
            <category><![CDATA[policy]]></category>
            <category><![CDATA[equality]]></category>
            <category><![CDATA[justice]]></category>
            <category><![CDATA[video-games-industry]]></category>
            <category><![CDATA[accessibility]]></category>
            <dc:creator><![CDATA[Ben Roston]]></dc:creator>
            <pubDate>Sat, 23 Dec 2023 16:45:02 GMT</pubDate>
            <atom:updated>2023-12-23T22:51:19.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cufIbkD7FoZiyUDo" /><figcaption>Photo by <a href="https://unsplash.com/@kommumikation?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Every time a new game from From Software, developers of hall of fame video games like Dark Souls, Elden Ring, and most recently Armored Core VI, the gaming community erupts in a debate about difficulty in video games. For the uninitiated, From Software is notorious for incorporating excruciating difficulty as a formalized feature of its games. Players expect it; thirst for it, even. There’s something special about fighting a boss hundreds of times only to beat it on the hundred and first attempt. Unfortunately, the harsh challenge is often a real barrier to players interested in playing these games to the end but simply cannot get past an early game boss (Bloodborne’s <a href="https://bloodborne.fandom.com/wiki/Father_Gascoigne">Father Gascoigne</a> is one of the game’s hardest bosses while also being only the second boss). For a not insignificant amount of players, these extreme difficulties make these games genuinely inaccessible. In other words, difficulty is a real barrier to access for players wanting to enjoy a game they purchased.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7oDM2-Swo6eZ2hUk" /><figcaption>Photo by <a href="https://unsplash.com/@kike_borland?utm_source=medium&amp;utm_medium=referral">Enrique Guzmán Egas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The question at the heart of these debates is whether or how a game mechanic that doubles as a barrier to access to some players while improving the experiences of others can be fair or just. This author does not dare enter the fray of video game debates (… online arguments, screaming matches, etc.), but the topic is a fruitful space to explore the nuances of fairness. After all, what do we mean when we say something is “fair”? While we’re at it, what is the “something” whose “fairness” is being measured?</p><p>In the book<strong> </strong><a href="https://www.amazon.com/Policy-Paradox-Political-Decision-Making-dp-0393912728/dp/0393912728/ref=dp_ob_title_bk"><strong>Policy Paradox</strong></a>, Deborah Stone begins answering these questions with a famous quote in the policy sphere, sharing that political science is “the study of ‘who gets what, when, and how?’” (originally penned by Harold Lasswell in 1958). In the context of video game difficulty we may ask “who gets access to an enjoyable gaming experience, when, and how?” Two options for the “how” come to mind from our example. Some gamers get an enjoyable gaming experience through overcoming challenge. On the other hand, others get an enjoyable gaming experience through experiencing a game’s story regardless of its difficulty. In the case of a game like Dark Souls which does not have difficulty options, the game developers are left with a zero-sum choice where the gain of one group means the loss of the other. Reducing the game’s difficulty improves the experience for some while harming the experience of others and vice versa for increasing its difficulty. In reality, this is probably more of a business decision than a stereotypical policy debate, but it is nonetheless an interesting example in equity and fairness (in video games and beyond)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xXHUZ-Rfylnlpldb" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The phrase “get good” is overwhelmingly prominent in the discussions about video game difficulty (to a meme-ified extent). It represents the idea that players of different skill levels should have different access to what a video game has to offer. In particular, if players want to experience a challenging game to the end, then the burden is on them to “get good” (or “git gud” for the haters). It suggests that the game offers the opportunity for players to have equal experiences so long as each player is willing to put in a (likely high) specific amount of effort, presenting effort alone as the critical barrier to access.</p><p>It is admittedly curious to see that the “get good” philosophy, an argument often used to express that a game is only accessible to the realest of real gamers, is itself rooted in a type of equality. Stone describes this distribution of experiences (or goods, services, etc.) as <strong>Unequal Slices for Unequal Merit</strong>. Here, equality is defined by the idea that people who put in different amounts of effort should receive different amounts of some reward (or goods, services, etc.). It’s typical to see this kind of equality proposed in pro-meritocracy economic discussions, where one might argue that wealth is a measure of one’s merit or financial prowess alone and does not reflect broader systemic inequalities. For a closer to home example, consider the last time you had that one partner in a group project who clearly didn’t contribute as much to the project as the rest of the team. When wondering if it would be more just for them to get a different grade for a different amount of work, you are applying the Unequal Slices for Unequal Merit philosophy.</p><p>The question is widely debated whether constructing access to challenging video games as an effort-based meritocracy creates a just gaming experience. However, the question remains, “just” for who, and how?</p><p>Perhaps every game should define success by lottery. Every player has an “equal” chance of having a positive experience based on some dice roll somewhere within the game’s code (ignoring bonuses to dice rolls that games like Baldur’s Gate 3 are based on; here every player regardless of in-game decisions has the exact same probability of experiencing success).</p><p>Alas, leaving success in video games to random chance creates an extremely unsatisfying gameplay loop. If triumph over a video game opponent is left purely to a lottery system then where’s the fun? To be fair (and that’s what we’re going for), this is probably the most egalitarian option. After all, what’s more equal than a coin flip? Unfortunately, while this option guarantees that every player has an equal chance of success, many will be left disappointed with the experience (though admittedly this might be the ideal game experience for some).</p><p>Stone describes this kind of equality as <strong>Unequal Slices but Equal Statistical Chances of Winning</strong>. We might encounter this kind of system in immigration policy, particularly in receiving work visas for international residents. These can take the form of a lottery system where only a certain number of visas can be granted and applicants have an X% chance of successfully attaining one.</p><p>Some games address the challenge of making games accessible to players across a wide range of skill levels by implementing a difficulty level system. These might be separated between beginner, novice, and expert difficulty levels (or “Give me God of War” for those with a certain interest in self-infliction). Difficulty modes let players give players an array of gaming experiences to choose from, making the game accessible to players across a wide array of skill levels.</p><p>Arguments in favor of implementing difficulty levels for notoriously challenging games implement what Stone calls <strong>Unequal Slices but Equal Value to Recipients</strong>. Inevitably, different difficulty levels will provide players with different (and thus unequal) experiences, but they ensure that every player has access to everything a game has to offer. In other words, every player has access to experience the entirety of a game they paid for, but they may choose to experience the game differently (on different difficulty levels). While seemingly ideal for players, leaving ambiguous <a href="https://www.youtube.com/watch?v=-nJtd8AJghM">which mode a game is meant to be played</a> can create a real challenge in balancing the game across all difficulty levels from the developer side.</p><p>Imagine two patients preparing for the same costly surgery asking for financial assistance, where one can independently cover more of the cost of the procedure than the other. A fair distribution of aid under the Unequal Slices but Equal Value to Recipients philosophy would be to give each patient however much they need to pay for the surgery. Of course, the patient who can independently pay for more of the cost will receive less aid than the other patient who needs more financial assistance, but they both receive the same level of health care in the end.</p><p>Now, let’s consider players on the outer fringes of skills like speedrunners (or players touching video games for the first time on the other end of the scale). Speedrunners are the best of the best, capable of achieving the <a href="https://www.youtube.com/watch?v=7rIJNT7dCmE&amp;t=5s">human limit</a> of what’s possible. Should game difficulty be tuned to their skill level? Probably not, because most of us are not speedrunners (the closest I’ve gotten has been getting to the final boss in Sekiro in 4 and a half hours). We don’t necessarily want to create a gaming experience, though, that excludes players actively seeking a high difficulty ceiling, but at the same time speedrunners should still be able to have enjoyable experiences.</p><p>Speedrunners are notorious for using glitches and button-input techniques that mere mortals cannot fathom attempting. In other words, what makes a game enjoyable for speedrunners is often a totally inaccessible experience to players experiencing a game as-is. Maybe counterintuitively, this feels just. Even though players of different skill levels experience the game differently, players of different skill groups are allowed to experience the game as however they like.</p><p>Stone describes this setup as <strong>Unequal Slices but Equal Social Blocs </strong>(think of social blocs as a group with similar characteristics and/or interests). This frame proposes that inequality is fair so long as it corresponds to some distribution of groups. Studies on environmental justice, criminal justice, and many others focusing critically on equity distributions observe inequality through this lens. How is flood risk distributed across neighborhoods with different racial and financial makeups? What about crime statistics or arrest records? How does the number of incarcerated residents compare between white and <a href="https://www.vox.com/2020/6/30/21300294/bipoc-what-does-it-mean-critical-race-linguistics-jonathan-rosa-deandra-miles-hercules">BIPOC </a>residents and how does that distribution compare to the percentage of each group in the broader population?</p><p>A game implementing Unequal Slices but Equal Social Blocs would create a gaming experience that is enjoyable to the average player while also incorporating positive, yet different, experiences for new players and speedrunners alike. The Super Mario Brother games are excellent examples of this kind of design (there’s a reason these games are so prominent in the gaming community and pop culture as a whole).</p><p>This post does not answer the question of what a fair way to handle game difficulty may look like. Rather, it provides a few examples of different ways games, and real-world policies, can achieve some seemingly fair representation of equality while still being unequal in some respects. Only four such examples are given here, but Stone suggests at least nine different ways to achieve “equality” justly, meaning this feels like a complicated topic because it IS a complicated topic. Instead of framing discussions about fairness in video games (and policy) in terms of absolute equality, we can begin to take a more nuanced look at all the different ways we can achieve “equality,” and who that benefits or harms, when, why, and how.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IXMGddkwF5TjxjkV" /><figcaption>Photo by <a href="https://unsplash.com/@mike_meyers?utm_source=medium&amp;utm_medium=referral">Mike Meyers</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4d919f08134" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Words to Improve Your Technical Discussions]]></title>
            <link>https://medium.com/@ben.roston/3-words-to-improve-your-technical-discussions-7ad368b83f19?source=rss-43d56b97a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ad368b83f19</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[technical-writing]]></category>
            <category><![CDATA[graduate-school]]></category>
            <dc:creator><![CDATA[Ben Roston]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 01:58:25 GMT</pubDate>
            <atom:updated>2024-02-29T15:49:29.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T40mWUE_Oi9F_Jng" /><figcaption>Photo by <a href="https://unsplash.com/@lunarts?utm_source=medium&amp;utm_medium=referral">Volodymyr Hryshchenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If a picture is worth a thousand words, what does that make for the world around us? Like our senses of touch and smell, language and communication are fundamental to the way we navigate throughout the human experience. Language is built on words which construct sentences like “That hot sauce is extra spicy,” or “It’s raining cats and dogs” to communicate feelings and observations to one another.</p><p>Over the years, and particularly recently with the onslaught of ChatGPT, it feels like we are constantly bombarded with breaking news, new technologies, new types of problems, new … JavaScript frameworks, with little to parse them in terms of their value to our many projects.</p><blockquote>“scientific information is likely to be effective in influencing the evolution of social responses to public issues to the extent that the information is perceived by relevant stakeholders to be not only credible, but also salient and legitimate” (Cash et al. 2003, p. 8068).</blockquote><p>Consider, now, the major questions we ask in the face of new ideas: What does it matter? Does it work? and maybe Who’s the audience? These are the same things people both within and outside computer science and engineering disciplines wonder when engaging with technical information. Commenting on the what makes technical information communication more effective, a group of well-known authors in the Science and Technology space write distinguish between three core variables, credibility, legitimacy, and salience (<a href="https://doi.org/10.1073/pnas.1231332100">Cash et al. 2003</a>) (See Table 1).</p><p><strong>Credibility</strong> is “the scientific adequacy of the technical evidence and arguments.” Does the work check all the boxes, so to speak? Does it use the best validation strategies or Does it follow disciplinary norms? Academic journals get a sense of credibility via their peer-review process. As an audience, when we see that multiple experts have approved an article, we perceive that the work meets a level of scientific and technical rigor.</p><p><strong>Legitimacy</strong> depicts a sort of fairness. Unlike credibility, legitimacy is largely subjective. Information is legitimate when it is <em>perceived</em> to be “respectful of stakeholders’ divergent values and beliefs, unbiased in its conduct, and fair in its treatment of opposing views and interests.” We encounter this term frequently in politics, like where more partisan decisions tend to be <em>perceived</em> as less legitimate than say those with bipartisan support. Legitimacy is also derived from the considered sample. Studying samples representative of the population, for example, may be <em>perceived</em> as more legitimate than more homogeneous samples (ex. Facial recognition AI trained on a mostly white, male sample lacks legitimacy because it is highly exclusionary).</p><p><strong>Salience</strong> describes relevance. It is “the relevance of the assessment [or information] to the needs” of the audience. Similar to legitimacy, salience is defined by the audience, where salient information is information that some audience <em>perceives</em> to be relevant. In the frenzy of generative AI news, articles on ChatGPT were and remain highly salient to the tech audience. My expertise in water resources engineering may be salient to a flood risk task force but perhaps not as much to this reader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caR5iYhxFBDPQ83tJgNDhQ.png" /><figcaption>Tab. 1 Salience, Credibility, and Legitimacy as defined by Cash et al. (2003)</figcaption></figure><p>Any communication to both technical, interdisciplinary, and public audiences can be described in terms of Salience, Credibility, and Legitimacy. Note, though, that any and every combination of these qualities has value across different settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_6RMrycOwb5NilKu436Kw.png" /><figcaption>Figure 1. Synergy of Credibility, Legitimacy, and Salience</figcaption></figure><p>We’ve already talked about the credibility of scientific articles, but especially among technical disciplines, scientists also aim to have their work be perceived as legitimate by highlighting their “objectivity.” Op-ed pieces may favor salience over legitimacy to target or appeal to specific audiences. Remember, that salience and legitimacy are in the eye of the beholder. The average person may not find a comparison of the garbage collectors in C++ vs Go particularly salient, although it may be thoroughly credible and legitimate.</p><p>Although they go together frequently, credibility and legitimacy represent different qualities and do not always necessarily go together. Partisan Think Tank studies can be thoroughly credible while also being perceived as illegitimate from opposing parties. Likewise, a report may be legitimate in comparing multiple policy options, but if it doesn’t have references, data, or any signs of analysis, then it would not be particularly credible.</p><p>Cash and colleagues popularized Credibility, Legitimacy, and Salience as tools to discuss the value of different arguments, articles, and broader studies from multiple perspectives. Is there a problem with an article’s application of methods? Then we need to discuss its credibility. Does it treat competing perspectives fairly? Now we’re talking about legitimacy. Lastly, is it relevant to the broader discussion on whatever topic we may be interested in? Salience. Most if not all work can be described in terms of these three powerful words.</p><p><strong>References</strong></p><p>Cash, D.W., Clark, W.C., Alcock, F., Dickson, N.M., Eckley, N., Guston, D.H., Jäger, J., Mitchell, R.B., 2003. Knowledge systems for sustainable development. Proceedings of the National Academy of Sciences 100, 8086–8091.. <a href="https://doi.org/10.1073/pnas.1231332100">https://doi.org/10.1073/pnas.1231332100</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DUXS-u0ifFkKbUDM" /><figcaption>Photo by <a href="https://unsplash.com/@priscilladupreez?utm_source=medium&amp;utm_medium=referral">Priscilla Du Preez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you found this post helpful, give a like and a follow :) Grad student in the woes of the middle of the semester, so probably one or two articles a month until the Summer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ad368b83f19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exponential Random Graph Models (ERGMs), Network Analysis, and You]]></title>
            <link>https://medium.com/@ben.roston/exponential-random-graph-models-ergms-network-analysis-and-you-2d7d756345e8?source=rss-43d56b97a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d7d756345e8</guid>
            <category><![CDATA[network-analysis]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Ben Roston]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 00:00:30 GMT</pubDate>
            <atom:updated>2023-02-09T21:45:48.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OoP3qkWxM_O-j-tcPXxUmA.png" /><figcaption>from <a href="https://www.bookotrip.com/sights-and-shores/wp-content/uploads/2017/09/World-map-with-infographic-airplane-route-concept-shutterstock_145341472-Converted-1024x512.png">bookotrip.com</a></figcaption></figure><p>Say we have a friend group of 50 students that is extremely close to where almost every student is friends with all the other students. This is an exaggeratedly dense network, and one where gossip would spread like wildfire. As an outsider, we may find ourselves asking if there is some explanatory variable that has made this friend group so close (perhaps a similar interest in Dungeons and Dragons or more structural characteristics like having many people who are all central to the group), or if this highly dense network is what we may expect just by chance? In this article, we’ll use flight data to explore how we can use ERGMs to perform similar comparisons to our friend group example.</p><h4>Flights Data</h4><p>Before diving into the math, this article uses <a href="https://www.kaggle.com/datasets/thedevastator/global-air-transportation-network-mapping-the-wo?select=routes.csv">Kaggle flight route data</a> to illustrate an ERGM example. Luckily, we don’t need to clean up the data very much, just select the source and target airport variables and change their names to “source” and “target” to be able to work with R’s network package (for info on network, check out a previous post on <a href="https://medium.com/@ben.roston/network-analysis-tools-in-r-and-python-w-marvel-superheroes-800bfe412700">network analysis tools in Python and R</a>).</p><pre>library(dplyr)<br>library(igraph)<br><br># load .csv<br>data &lt;- read.csv(file)<br><br># select the Source and Destination airport columns<br>edgelist &lt;- data %&gt;%<br>  select(Source.airport, Destination.airport)<br><br># rename columns to work with igraph functions<br>colnames(edgelist) &lt;- c(&quot;source&quot;, &quot;target&quot;)<br><br># load edgelist into an networkobject<br>flights &lt;- network(edgelist, loops = TRUE, multiple = TRUE)</pre><h3>Theory</h3><p><em>ERGM are graphical models built from the Exponential Family that describe how patterns in an observed network are related to various network statistics.</em></p><h4>Exponential Family</h4><p>The “E” in ERGM comes from its foundation in the <a href="https://www.cs.columbia.edu/~blei/fogm/2015F/notes/exponential-family.pdf">Exponential Family of functions</a>. You may not have heard them described this way before, but some of the most common statistical distributions fall within the Exponential Family like the binomial, poisson, and even standard distributions. Exponential Family means that a given distribution can fit into the form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FJwvk1FQPttMKPU73TR3Q.png" /><figcaption>Equation 0. General form of a Probability Density Function for an Exponential Family Model (Blei, 2015)</figcaption></figure><p>The above equation defines the probability of observing x given some weighted parameter set 𝜃 along some set of explanatory variables t(x). In our friend group example, x would be the density (or how many connections there are between friends) and the variable set t(x) would include our potential explanatory variables (i.e. interest Dungeons and Dragons or structural characteristics), and 𝜃 would describe the weights of how impactful each variable is on the observation.</p><p>Don’t worry if that doesn’t sink in. Exponential Family theory is a whole topic on its own and is still frankly a little over my head even after having dove into it for a little bit. Equation 0 is meant for those interested in having a fundamental starting point that grounds where most other resources tend to start their <a href="https://statnet.org/workshop-ergm/ergm_tutorial.html">ERGM walkthrough.</a></p><h4>ERGM Fundamentals</h4><p>An ERGM takes the general form of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quG2GqRG5p8zRhVwscsi8w.png" /><figcaption>Equation 1. General Form of an ERGM (replace t(x) with g(y) and a(𝜃) with k(𝜃). h(x) = 1)</figcaption></figure><p>where:</p><ul><li>p(<strong>Y</strong> = y) is the probability that a random graph <strong>Y</strong> is equivalent to the observed graph y</li><li>g(y) is a vector of network statistics (covariates) that help predict the observed graph y (network density, number of dyads, etc.)</li><li>𝜃 is a vector of coefficients that describe the impact of a corresponding network statistic in g(y) on the probability of the observed graph occurring</li><li>k(𝜃) is summation of the numerator over all possible networks, i.e. the integral of the numerator over all possible networks</li></ul><p>The general form is fairly abstract, but let’s walk through it. First, notice that the numerator takes the exponential of the <strong>dot product</strong> of the transverse of 𝜃 and g(y). Expanding the dot product and taking its logarithm to remove the exponential makes the numerator look more like a logistic regression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcdjsZru2qb33Pu87m1hFA.png" /><figcaption>Equation 2. Regression-like form of the numerator in the general form equation of an ERGM (Eq. 1)</figcaption></figure><p>Remember, g(y) is a vector of network statistics and 𝜃 is a vector of the impacts of those network statistics on the likelihood of observing a given graph. In our model, we know g(y). It could be a vector of {number of dyads, betweenness centrality}. Then, our ERGM would estimate the values of 𝜃.</p><p>Let’s look at what using ERGMs looks like in practice. The ergm and network packages, part of the statnet suite in R will be our tools throughout this exercise.</p><p>R has a straightforward syntax in modelling relationships between a set of covariates and a dependent variable using the ~ operator</p><pre>dependent_var ~ var_1 + var_2 + ... + var_n</pre><p>In the language of ERGMs, {var_1, var_2, … , var_n} is the vector of network statistics g(y) that impact the dependent variable. In our case, the dependent variable is the observed graph.</p><pre>observed_graph ~ network_stat_1 + network_stat_2 + ... + network_stat_3</pre><p>The observed graph is the actual data. Here, the flights network is our observed graph. Setting g(y) = {density}, then, elicits: flights ~ density . Right now, there are no probabilities involved. If we ran the summary function on this equation, it would return the network density of the flights data</p><pre>&gt; summary(flights ~ density)<br><br>    density <br>0.003205795</pre><p>flights has a network density of around 0.003. That is, the number of edges present represent just 0.3% of the maximum possible number of edges in the network.</p><p>Now, what if we wanted to know how this observed density value compares to the density of a graph with similar attributes to flights . What if we wanted to ask how much of our observed density is due to the chance of a network with similar attributes having the same density? In short, how can we know how our observed network density compares to chance?</p><p>This is the same question we ask when using Bootstrapping methods to determine how likely an observed metric is observed due to chance. Since ERGMs are closely related to Bootstrapping, let’s run through a brief review of the method using the mpg variable in the mtcars dataset.</p><h4>Review: Bootstrapping</h4><p>Say we found the mean mpg in the data to be around 20.1, and wanted to know how well this is representative of the population. Additionally, if the distribution of fuel efficiency across cars is skewed, then we want to know if the mean is at all descriptive of the population. Bootstrapping involves pulling a large number of random samples (with replacement) from our distribution, calculating our statistic of interest (mean) and then comparing how this distribution of means compares to our observed mean (~20.1mpg). Here’s the code</p><pre>mpg &lt;- mtcars$mpg<br><br># observed statistic<br>obs_mean &lt;- mean(mpg) # about 20.1<br><br>nsims &lt;- 1000 # or some other large number<br><br># create an empty vector to store simulated means<br>sim_means &lt;- data.frame(<br>  &quot;means&quot; &lt;- vector(length = nsims)<br>)<br><br>sample_size &lt;- 20 # or some number smaller than the amount of datapoints<br><br>for (i in 1:nsims) {<br>  # pull a random sample from the distribution<br>  sample_set &lt;- sample(mpg, size = sample_size, replace = TRUE)<br>  # store the mean of the random sample (simulated mean)<br>  sim_means$means[i] &lt;- mean(sample_set)<br>}<br><br># plot the distribution of simulated means<br># compare with the observed mean<br>ggplot(sim_means) +<br>  geom_histogram(aes(x = means)) +<br>  geom_vline(aes(xintercept = obs_mean)) + <br>  theme_classic()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTFT2jWfQ7gRtotGmWyCOg.png" /><figcaption>Distribution of simulated means over the mpg variable in the mtcars dataset</figcaption></figure><p>Using the quantile() function, we can get the 95% confidence bounds across our simulated means. This gives us a more flexible estimate of the observed mean because instead of a point, we will have a range of values in which we are 95% confident that the mean is within.</p><pre># 95% confidence interval (CI)<br>CI_025 &lt;- quantile(means$mean, 0.025)<br>CI_975 &lt;- quantile(means$mean, 0.975)<br><br># plot observed mean with confidence interval on original data<br>ggplot(mtcars) +<br>  geom_histogram(aes(x = mpg), bins = 5, alpha = 0.75) +<br>  geom_vline(aes(xintercept = mean_mpg, color = &quot;red&quot;)) +<br>  geom_vline(aes(xintercept = CI_025, color = &quot;red&quot;), lty = &quot;dashed&quot;) +<br>  geom_vline(aes(xintercept = CI_975, color = &quot;red&quot;), lty = &quot;dashed&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ssS07A2dt5ggEiFgopdXQ.png" /><figcaption>Distribution of fuel efficiency with mean fuel efficiency and its 95% confidence interval</figcaption></figure><p>Although ERGMs are NOT built to define confidence intervals, they apply a similar simulation methodology to describe, not necessarily how descriptive a statistic is of a network, but rather how that statistic compares across simulated networks of like characteristics. Let’s expand on our example to visualize this nuance.</p><p>There are 32 observations in our mpg data that range from [10.4, 33.9]. What is the distribution of means we can expect from samples with similar characteristics to our observation data? In the sense of Equation 2, g(y) = {n_observations, minimum, maximum}.</p><pre># characteristic statistics of the obs data<br>n_obs &lt;- length(mpg)<br>min_obs &lt;- min(mpg)<br>max_obs &lt;- max(mpg)<br><br>n_sims &lt;- 1000 # or some other large number<br><br># set up empty dataframe<br>sims &lt;- data.frame(<br>  matrix(ncol = n_sims, nrow = n_obs)<br>)<br><br>for (i in 1:nsims) {<br>  # pull from a uniform distribution with<br>  # characteristics similar to our data<br>  samples &lt;- runif(n_obs, min_obs, max_obs)<br>  sims[,i] &lt;- samples<br>}<br><br># get the means for each simulated sample<br>means &lt;- apply(sims, 2, mean)<br><br># compare means from the samples to the observed mean<br>ggplot() +<br>  geom_histogram(aes(x = means)) + <br>  geom_vline(aes(xintercept = mean_mpg, color = &quot;red&quot;)) +<br>  theme_classic()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJN-gdAMAbbRH3Dp4couDw.png" /><figcaption>Distribution of means from samples with characteristics similar to the observed data</figcaption></figure><p>Our analysis suggests that data with similar characteristics to ours tends to result in a slightly higher mean than that in our observed data (~22.5 vs ~20.1). That’s an interesting finding! And one that holds a lot of weight when applied in the frame of network analysis.</p><h3>Getting Started with Coding ERGMs</h3><p>We just looked at an example comparing an observed statistic with statistics simulated from samples with like characteristics (g(y)) as the observed data. With ERGMs, we ask: given a sample of networks with like characteristics as the observed network (g(y)), what is the likelihood that these simulations produce the observed network? Like we compared the observed mean with simulated means above, we can compare the observed network statistics with statistics from simulated networks with like characteristics.</p><p>Let’s see this in practice. The function summary(flights ~ edges) returns the number of edges in flights , n_edges = 37,595. Say we are interested in the number of triads (three-node cycles) in flights . We can calculate the observed number of triads via summary(flights ~ cycle(k = 3)) which returns n_triads = 197,461. That’s a lot of triads! So, we may want to ask ourselves, given a bunch of random networks with of a similar size, how many would have 197,461 triads?</p><p>This is analysis will follow four steps:</p><ol><li>Create the ERGM</li><li>Create simulations based on the ERGM</li><li>Measure the network statistic of interest from the simulations</li><li>Compare the distribution of empirical network statistics with the observed network statistic</li></ol><h3>1. Create the ERGM</h3><p>The ergm package makes ERGM creation fairly straightforward using the ergm function. For our example,</p><pre>flights_ergm &lt;- ergm(flights ~ edges)<br>flights_ergm</pre><pre>[1] &quot;Warning:  This network contains loops&quot;<br>Starting maximum pseudolikelihood estimation (MPLE):<br>Evaluating the predictor and response matrix.<br>Maximizing the pseudolikelihood.<br>Finished MPLE.<br>Stopping at the initial estimate.<br>Evaluating log-likelihood at the estimate. <br><br>Call:<br>ergm(formula = flights ~ edges)<br><br>Maximum Likelihood Coefficients:<br>edges  <br>-5.74  </pre><p>The details behind the ergm function itself are better for another day because we only need the Maximum Likelihood Coefficient info at the bottom. It looks funky though. What exactly does a coefficient of -5.79 for the edges network statistic mean? Remember that the edges coefficient is a part of the vector of coefficients 𝜃 from Equations 1 and 2, and g(y) = {edges} in our example. So, we can write our results in the form of Equation 2 (since only one network is used to formulate the ergm, k(𝜃) = 1, so only the numerator is left)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*C3_5p4upqnt9G0lV4tHJCQ.png" /></figure><p>We can actually plot this out to see what it looks like. After all, we have a value for 𝜃 (-5.74), leaving an x-variable (edges) to plot against (see figure below). The above function is an exponential function. Like in logistic regression, taking the log-odds of the exponential function returns a linear function which has a slope equivalent to 𝜃.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pH_HxwY4SROvW7bn5OMzA.png" /><figcaption>Left: Probability of an Edge Occurring if an Edge is Added. Right: Log-Odds of an Edge Occurring if an Edge is added.</figcaption></figure><p>Working backwards from log-odds, we can calculate what 𝜃 means as a probability by taking its <a href="https://medium.com/wicds/logistic-regression-understanding-odds-and-log-odds-61aecdc88846">inverse-log odds (expit</a>) which is 1/(1-exp(-𝜃)), which gives us a value of 0.0032.</p><p>Wait a minute! 0.0032? As in the density of the network we calculated earlier??? What’s going on here?! P(<strong>Y</strong> = y) can take on two meanings, the first is the probability of observing a specific graph and the other is the probability of observing a tie between any two nodes. Network density is the ratio of the number of edges to the maximum possible number of edges… which sounds a lot like a probability. That ratio exactly describes the probability of an edge occurring between any two nodes, which is exactly what our ERGM told us!</p><h3>2. Create simulations based on the ERGM</h3><p>This is the Bootstrapping step of an ERGM analysis, and is fairly standardized in the ergm package using the simulate() function</p><pre>simulate(<br>  flights_ergm, # the ergm<br>  nsim = 100, # number of simulated networks<br>  # set parameters for MCMC<br>  control = control.simulate.ergm(<br>    MCMC.burnin = 500000, # or some very large number<br>    MCMC.interval = 25000 # half of burnin<br>  ),<br>  verbose = FALSE # don&#39;t show everything in console<br>)</pre><p>simulate() takes as inputs an ergm object and the number of simulated networks you want it to produce. The MCMC values in the control function manage the Markov Chain Monte Carlo simulations that are outside the scope of this article. All you need to understand is that those values should be fairly large numbers. The above function returns the following object</p><pre>Number of Networks: 100 <br>Model: flights ~ edges <br>Reference: ~Bernoulli <br>Constraints: ~. </pre><p>This object is a collection of network objects corresponding to each of our newly simulated networks. We can look at each of them individually by indexing the simulations</p><pre>&gt; flights_ergm_sims[[24]]<br><br> Network attributes:<br>  vertices = 3425 <br>  directed = TRUE <br>  hyper = FALSE <br>  loops = TRUE <br>  multiple = TRUE <br>  bipartite = FALSE <br>  total edges= 37899 <br>    missing edges= 0 <br>    non-missing edges= 37899 <br><br> Vertex attribute names: <br>    vertex.names <br><br> Edge attribute names not shown </pre><p>Notice the total nodes in the simulated network equals the number of nodes in our observed network, but the total edges value is different. That’s because the way ergm works is that its simulations begin with an empty network with the number of nodes in the observed network (3,425) and then gives every possible edge a probability of occurring like a coin flip. Once its “flipped a coin” for every possible edge, it measures how many edges are present, and for the above model it appears that the simulation created 37,899 edges (vs our observed 37,595 edges).</p><h3>3. Measure the network statistic of interest from the simulations</h3><p>Now it’s time to analyze our simulations. Like when we calculate the mean of each random sample in Bootstrapping, we now need to calculate our network statistic-of-interest for each of our simulated networks. Remember, our statistic-of-interest or dependent variable is the number of triadic cycles in the network.</p><p>At this point we’re working outside the ergm library and more with network and general R functions</p><pre>simulated_n_triads &lt;- sapply(<br>  flights_ergm_sims, <br>  function(sim_network) summary(sim_network ~ cycle(3))<br>)</pre><h3>4. Compare the distribution of empirical network statistics with the observed network statistic</h3><p>Let’s plot a histogram of simulated_n_triads to see what kind of distribution we’reworking with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6do_WAJECZU72vMTw_-GeA.png" /><figcaption>Distribution of the number of triadic cycles in the 100 simulated networks</figcaption></figure><p>Okay, looks like a mean around 440 with a general range from 410–480 triads. Seems reasonable. Let’s go ahead and compare that with our observed value for the number of triadic cycles of… 197,461! Woah! that is some significant difference, like magnitudes of difference. Our results are telling us that networks with the name number of nodes as flights are tend to have significantly less triadic cycles by chance.</p><p>To be fair, it’s surprising to see this staggering of a difference between our observed and simulated values, but it can at least be explained. If airlines setup their routes so that planes move in triangular paths between airports most of the time, say New York to DC, DC to Minneapolis, then Minneapolis back to New York, then this is the exact kind of result from our ERGM that we would expect to see.</p><h3>Closing Thoughts</h3><p>ERGMs are powerful tools that can explore how randomness plays a role in observations within our network data while letting us perform a pseudo-regression across network statistics. The ergm and network packages by the great folks behind statnet are thorough and well-documented tools to help anyone interested in getting started or even pushing the limits of what ERGMs can do for us.</p><p>ERGMs are some of the hardest statistical tools I have come across in grad school so far and it has taken me a good month or two to get this far into being able to explain it to some level of detail. Don’t be worried about feeling intimidated with the formulas if they don’t make sense immediately… or longer than immediately. A pen and paper are your best tools for working out the gaps between steps to really understand the nitty-gritty. The ergm and network packages are stellar tools and their are an abundance of tutorials that the authors have provided to help you get your analysis up and running.</p><p>Lastly, for those with expertise on ERGMs or general comments, please please please let me know if anything I’ve said in this article looks off or just could be improved. There’s a lot of moving parts with ERGMs and I want to make sure this post represents them all accurately and clearly.</p><h4>Citations for the ergm and network packages</h4><p>Handcock M, Hunter D, Butts C, Goodreau S, Krivitsky P, Morris<br> M (2022). _ergm: Fit, Simulate and Diagnose Exponential-Family<br> Models for Networks_. The Statnet Project<br> (&lt;<a href="https://statnet.org/">https://statnet.org</a>&gt;). R package version 4.2.2,<br> &lt;<a href="https://cran.r-project.org/package=ergm">https://CRAN.R-project.org/package=ergm</a>&gt;.</p><p>Butts C (2015). _network: Classes for Relational Data_. The<br> Statnet Project (&lt;<a href="http://www.statnet.org/">http://www.statnet.org</a>&gt;). R package version<br> 1.13.0.1, &lt;<a href="https://cran.r-project.org/package=network">https://CRAN.R-project.org/package=network</a>&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m2VTQEy8jllWp_Qv" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you found this post helpful, give a like and a follow :) I’m hoping to keep up at least a bi-weekly pace throughout the semester.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d7d756345e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Network Analysis Tools in R and Python w/ Marvel Superheroes]]></title>
            <link>https://medium.com/@ben.roston/network-analysis-tools-in-r-and-python-w-marvel-superheroes-800bfe412700?source=rss-43d56b97a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/800bfe412700</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[network-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Ben Roston]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 19:48:48 GMT</pubDate>
            <atom:updated>2023-01-27T19:48:48.736Z</atom:updated>
            <content:encoded><![CDATA[<p>This post uses <a href="https://www.kaggle.com/code/jaewook704/marvel-network">Marvel Superhero data from kaggle</a> that measures superheroes that appear in the same comic together. For example, Captain Marvel and Black Panther appear in the Avengers together, Doctor Strange and Spiderman in “No Way Home,” etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gAXK-zIwnInou9bb" /><figcaption>Photo by <a href="https://unsplash.com/fr/@introspectivedsgn?utm_source=medium&amp;utm_medium=referral">Erik Mclean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s begin by taking a look at the <a href="https://www.kaggle.com/datasets/csanhueza/the-marvel-universe-social-network?resource=download&amp;select=hero-network.csv">data (hero-network.csv)</a>. How many columns and rows does it have? What data types are present? Is the data continuous or categorical?</p><pre># Load data<br><br>import pandas as pd<br># tkinter helps handle file-selection through pop-up windows<br>from tkinter.filedialog import askopenfilename<br><br>data_file = askopenfilename() # opens pop-up window to select file<br>df = pd.read_csv(data_file)</pre><pre># get n_rows and n_cols<br>df.shape # (rows = 574467, cols = 2)<br><br># get column names<br>df.columns # (Index([&#39;hero1&#39;, &#39;hero2&#39;], dtype=&#39;object&#39;))<br><br># get data types<br>df.types<br># hero1    object -&gt; essentially a string<br># hero2    object<br># dtype: object<br><br># glimpse dataframe<br>df.head</pre><pre>                       hero1                 hero2<br>0              LITTLE, ABNER        PRINCESS ZANDA<br>1              LITTLE, ABNER  BLACK PANTHER/T&#39;CHAL<br>2       BLACK PANTHER/T&#39;CHAL        PRINCESS ZANDA<br>3              LITTLE, ABNER        PRINCESS ZANDA<br>4              LITTLE, ABNER  BLACK PANTHER/T&#39;CHAL<br>                     ...                   ...<br>574462  COLOSSUS II/PETER RA              CALLISTO<br>574463              CALLISTO               ROGUE /<br>574464              CALLISTO              CALIBAN/<br>574465              CALIBAN/               ROGUE /<br>574466  HULK/DR. ROBERT BRUC     MARKS, DR. SHIELA</pre><p>574,467 is a lot of rows and far beyond anything we want to do by hand! Luckily, even though there are a lot of records, there are only 2 columns (‘hero1’ and ‘hero2’). Each column for a record contains “object” data (pandas way of labeling strings) that lists a superhero. From the output of df.head , each row contains a different superhero in each column. Each record can be read as Hero2 appears in a Hero1 comic. For example, the third record represents the observation of <a href="https://www.marvel.com/comics/issue/17862/black_panther_1977_2">Princess Zanda and Black Panther appearing in the same comic</a>.</p><p>This dataframe is an example of an edgelist, a network data structure that lists edges between nodes, defined with an edge’s source node and target node. In the example, Black Panther is the source node and Princess Zanda is the target node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*epQBTbTEnjx-zesJ" /><figcaption>Photo by <a href="https://unsplash.com/@mullyadii?utm_source=medium&amp;utm_medium=referral">Mulyadi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Edgelist vs Adjacency List vs Adjacency Matrix.</strong></p><p>There are different ways to represent network data. The edgelist is just one. Adjacency Lists are organized by node, showing all the nodes that the source node connects to.</p><p>Adjacency Matrices are more difficult to read for the human eye, but can occasionally be easier to put together for analysis. These are n x n (square) matrices where each node is represented by a column and a row, showing every possible edge in the network. If an edge exists between two nodes, the value at the intersection of those two nodes in the matrix is set at 1, and if not, that edge is left at 0. These values can also take on any non-zero value to represent edge weights.</p><pre>Ex. Edgelist<br>[[Source, Target],<br>[A, B],<br>[A, D],<br>[A, C],<br>[B, C],<br>[C, E]]<br><br>Ex. Adjacency List<br>[<br>  {A: [B, C, D]},<br>  {B: [A, C]},<br>  {C: [B, E]},<br>  {D: [A]},<br>  {E: [C]}<br>]<br><br>Ex. Adjacency Matrix<br>  A B C D E<br>A 0 1 1 1 0<br>B 1 0 1 0 0<br>C 1 1 0 0 1<br>D 1 0 0 0 0 <br>E 0 0 1 0 0</pre><p>Each of these represent the same graph (below). It’s important to know which network data structure you are using for a given task, because most libraries have specific functions for working with either an edgelist OR an adjacency matrix. This is mainly limited to input and output data. The packages discussed in this post (R: Network and Python: NetworkX) both have their own “network” data structures that they use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*o_RqSyXeMwbp-VygTbTZrQ.png" /><figcaption>Network from the Example Data via NetworkX</figcaption></figure><p>Network Analysis and Network Visualization tend to be two separate stages of working with network data. Analysis involves the data wrangling and computations like calculating node degree, centrality, density, etc. NetworkX (Python), igraph (R), and Tidygraph(R) have extensive tools to analyze graph data. Each have a capacity to visualize networks too. visNetwork (R), on the other hand, is exclusively designed for network visualization. Finally, the folks at <a href="https://statnet.org/packages/">statnet</a> created a suite of packages to perform statistical tests on networks. These tests are for another post, but I’ll introduce the Network (R) package briefly just to share it here.</p><h3>Network Analysis</h3><h4><a href="https://networkx.org/">(Python) Networkx</a></h4><p>What makes a great package? Documentation and Test Coverage. NetworkX has both and is my preference for network analysis. It’s functions go well-beyond centrality measures, providing tools for cycle analysis, clusters, and traversals, with an extensive suite of random graph generation functions. The package has a great <a href="https://networkx.org/documentation/stable/tutorial.html">tutorial page</a> with detailed, <a href="https://networkx.org/documentation/stable/reference/index.html">accessible docs </a>that make finding answers to problems with it feel more efficient than other network packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*q8D-CtnSZjKUdZLWnqfiQw.png" /></figure><p>We begin by transforming raw data into a NetworkX networkx.classes.graph.Graph object. It looks more complicated than it is. This is just the package’s strategy of storing graph data. To transform our data, NetworkX needs to know what kind of data its getting from pandas, an adjacency matrix or an edgelist? Looking at our Marvel data, the raw data is in the form of an edgelist.</p><pre>import networkx as nx<br>marvel_network = nx.from_pandas_edgelist(df)</pre><p><em>This code will actually throw an error</em> because NetworkX needs the columns to have specific names: “source,” and “target.” Each package has their own requirements for what the edgelist column names needs to be but it is always some variation of source/target, to/from, etc. Rename the columns to fix the error and re-run.</p><pre>df = df.rename(columns = {&#39;hero1&#39;: &#39;source&#39;, &#39;hero2&#39;: &#39;target&#39;})<br>marvel_network = nx.from_pandas_edgelist(df)</pre><pre>In [4]: marvel_network<br>Out[4]: &lt;networkx.classes.graph.Graph at 0x7fe0343c6380&gt;</pre><p>marvel_network returns the class along with its location in memory. From here, we can get information from the network using object-oriented-style programming.</p><pre>marvel_network.nodes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DupsLCVo-ik-cZ30tEAaMg.png" /></figure><pre>marvel_network.edges</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_ZJhDqMSQswlPQr6gvN_g.png" /></figure><p>Information about the network takes the form network.data , while functions performed on the network takes the form function(network) . For example, nx.cycle_basis(network) “returns a list of cycles which form a basis for cycles” <a href="https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.cycles.cycle_basis.html#networkx.algorithms.cycles.cycle_basis">(from the docs)</a>.</p><pre>nx.cycle_basis(marvel_network)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*rhvKhWlhZboKwpvEaGqpzg.png" /><figcaption>One cycle in the basis of cycles for marvel_network</figcaption></figure><p>NetworkX has a lot to offer everyone from the beginner to experienced network analyst and provides detailed support for nearly everything you can ask for. Of the options on this post, NetworkX feels like the most complete network analysis package, given its strengths both in analysis and visualization. Although not mentioned here, check out information on <a href="https://networkx.org/documentation/stable/reference/drawing.html">drawing graphs with NetworkX’s Matplotlib integration in the docs.</a></p><h4><a href="https://igraph.org/r/">(R) igraph</a></h4><p>igraph works similarly to NetworkX where edgelists/adjacency matrices are transformed into igraph objects which can then be analyzed using the package’s many functions. igraph is available both on R and Python, but I tend to prefer using NetworkX when working in Python. igraph is great for those interested in analyzing network data for a project already rooted in R, where it would be inconvenient to translate the analysis across languages to use NetworkX (although <a href="https://medium.com/@ben.roston/r-vs-python-more-like-r-and-python-4f015fa57b6a">R does support cross-language functionality with the Reticulate package</a>). Like NetworkX, <a href="https://igraph.org/r/html/latest/">igraph has extensive docs</a> to guide users through its functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBNkz90Sbki830kSUM_45Q.png" /></figure><p>Beginning from loading the data into R, igraph’s input process is fairly straightforward:</p><pre># Load packages<br>library(igraph)<br>library(dplyr)<br><br># Load data<br>data_file &lt;- file.choose() # opens pop-up window to select file<br>df &lt;-read.csv(data_file)<br><br># Create igraph object<br>marvel_network &lt;- graph_from_data_frame(df)</pre><p>Note that here we transformed the data using graph_from_data_frame(df) instead of graph_from_edgelist as may have been expected. It’s a bit of a technicality. igraph’s graph_from_edgelist function requires we input a matrix datatype, but read.csv() returns a dataframe. Here’s how we could make graph_from_edgelist work:</p><pre>marvel_network &lt;- graph_from_data_frame(as.matrix(df))</pre><pre><em>&gt; marvel_network</em><br>IGRAPH 7b0f7c8 DN-- 6426 574467 -- <br>+ attr: name (v/c)<br>+ edges from 7b0f7c8 (vertex names):<br> [1] LITTLE, ABNER       -&gt;PRINCESS ZANDA       LITTLE, ABNER       -&gt;BLACK PANTHER/T&#39;CHAL<br> [3] BLACK PANTHER/T&#39;CHAL-&gt;PRINCESS ZANDA       LITTLE, ABNER       -&gt;PRINCESS ZANDA      <br> [5] LITTLE, ABNER       -&gt;BLACK PANTHER/T&#39;CHAL BLACK PANTHER/T&#39;CHAL-&gt;PRINCESS ZANDA      <br> [7] STEELE, SIMON/WOLFGA-&gt;FORTUNE, DOMINIC     STEELE, SIMON/WOLFGA-&gt;ERWIN, CLYTEMNESTRA <br> [9] STEELE, SIMON/WOLFGA-&gt;IRON MAN/TONY STARK  STEELE, SIMON/WOLFGA-&gt;IRON MAN IV/JAMES R.<br>[11] STEELE, SIMON/WOLFGA-&gt;RAVEN, SABBATH II/EL RAVEN, SABBATH II/EL-&gt;FORTUNE, DOMINIC    <br>[13] RAVEN, SABBATH II/EL-&gt;ERWIN, CLYTEMNESTRA  RAVEN, SABBATH II/EL-&gt;IRON MAN/TONY STARK <br>[15] RAVEN, SABBATH II/EL-&gt;IRON MAN IV/JAMES R. IRON MAN IV/JAMES R.-&gt;FORTUNE, DOMINIC    <br>+ ... omitted several edges</pre><p>There are many variations of names for nodes and edges across packages. igraph denotes a node as a <strong>Vertex</strong> and an edge as an <strong>Edge</strong>. The functions to get vertex and edge data are the first letter of each word:</p><pre>&gt; V(marvel_network)<br>+ 6426/6426 vertices, named, from 31fd55d:<br>   [1] LITTLE, ABNER        BLACK PANTHER/T&#39;CHAL STEELE, SIMON/WOLFGA RAVEN, SABBATH II/EL IRON MAN IV/JAMES R.<br>   [6] IRON MAN/TONY STARK  ERWIN, CLYTEMNESTRA  PRINCESS ZANDA       CARNIVORE/COUNT ANDR GHOST               <br>  [11] ZIMMER, ABE          FU MANCHU            SHANG-CHI            SMITH, SIR DENIS NAY STARSHINE II/BRANDY <br>  [16] MAN-THING/THEODORE T TARR, BLACK JACK     WU, LEIKO            JACKSON, STEVE       RESTON, CLIVE       <br>  [21] ROM, SPACEKNIGHT     DOCTOR DREDD         MYSTIQUE/RAVEN DARKH HYBRID/JAMES JIMMY M DESTINY II/IRENE ADL<br>  [26] ROGUE /              AVALANCHE/DOMINIC PE PYRO/ALLERDYCE JOHNN TORPEDO III/BROCK JO CLARK, SARAH        <br>  [31] CLARK, JOHN          JONES, DANIEL DANNY  JONES, NELL          JONES, LORRAINE LORR JONES, TAMMY ANNE   <br>  [36] KILLBURN, MACK       VASHTI               SUB-MARINER/NAMOR MA NOVA/RICHARD RIDER   SPIDER-MAN/PETER PAR<br>  [41] NIGHT THRASHER/DUANE HULK/DR. ROBERT BRUC SPEEDBALL/ROBBIE BAL NAMORITA/NITA PRENTI THUNDERBALL/DR. ELIO<br>  [46] JUSTICE II/VANCE AST FIRESTAR/ANGELICA JO TIGRA/GREER NELSON   QUICKSILVER/PIETRO M SCARLET WITCH/WANDA <br>+ ... omitted several vertices</pre><pre>&gt; E(marvel_network)<br>+ 574467/574467 edges from 31fd55d (vertex names):<br> [1] LITTLE, ABNER       -&gt;PRINCESS ZANDA       LITTLE, ABNER       -&gt;BLACK PANTHER/T&#39;CHAL<br> [3] BLACK PANTHER/T&#39;CHAL-&gt;PRINCESS ZANDA       LITTLE, ABNER       -&gt;PRINCESS ZANDA      <br> [5] LITTLE, ABNER       -&gt;BLACK PANTHER/T&#39;CHAL BLACK PANTHER/T&#39;CHAL-&gt;PRINCESS ZANDA      <br> [7] STEELE, SIMON/WOLFGA-&gt;FORTUNE, DOMINIC     STEELE, SIMON/WOLFGA-&gt;ERWIN, CLYTEMNESTRA <br> [9] STEELE, SIMON/WOLFGA-&gt;IRON MAN/TONY STARK  STEELE, SIMON/WOLFGA-&gt;IRON MAN IV/JAMES R.<br>[11] STEELE, SIMON/WOLFGA-&gt;RAVEN, SABBATH II/EL RAVEN, SABBATH II/EL-&gt;FORTUNE, DOMINIC    <br>[13] RAVEN, SABBATH II/EL-&gt;ERWIN, CLYTEMNESTRA  RAVEN, SABBATH II/EL-&gt;IRON MAN/TONY STARK <br>[15] RAVEN, SABBATH II/EL-&gt;IRON MAN IV/JAMES R. IRON MAN IV/JAMES R.-&gt;FORTUNE, DOMINIC    <br>[17] IRON MAN IV/JAMES R.-&gt;ERWIN, CLYTEMNESTRA  IRON MAN IV/JAMES R.-&gt;IRON MAN/TONY STARK <br>[19] IRON MAN/TONY STARK -&gt;FORTUNE, DOMINIC     IRON MAN/TONY STARK -&gt;ERWIN, CLYTEMNESTRA <br>+ ... omitted several edges</pre><p>If we want to see which superhero appears in the most comics with another hero, we can use igraph to get the degree of each Vertex and find the one with the largest value:</p><pre>degrees &lt;- degree(marvel_network) # get degree for each Vertex<br>max_degree &lt;- max(degrees) <br>degrees[degrees == max_degree] # return the Vertex with the largest degree</pre><pre>&gt; degrees[degrees == max_degree]<br>CAPTAIN AMERICA <br>          16499 </pre><p>Maybe not much of a surprise, but it looks like Captain America teams up with the most heroes with a whopping 16,499 team-ups!</p><p>igraph also has visualization capabilities that are slightly less organized in the docs compared to NetworkX, but still overall useful. There are great guides out there, though, to walk people through the visualization functions in the package. Check out <a href="https://robwiederstein.github.io/network_analysis/intro.html#creating-graphs">this chapter</a> from <em>Network Analysis in R</em> by <em>Robert Wiederstein </em>to get started.</p><h4>(R) Tidygraph</h4><p>Tidygraph is great for those experienced with R’s Tidyverse. The seller for Tidygraph is that it integrates itself with the Tidyverse packages like dplyr that make the data wrangling and analysis feel familiar. Having access to the pipe ( %&gt;% ) operator, in particular, helps Tidygraph feel more consistent with other data workflows in your R code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*NkpYbXrot4xPIpyLGf_caw.png" /></figure><p>It follows a similar process to transform data into Tidygraph’s version of a network object:</p><pre>library(tidygraph)<br>marvel_network &lt;- as_tbl_graph(df)<br># as_tbl_graph can handle both data.frame and matrix datatypes</pre><p>Fun Fact: <a href="https://tidygraph.data-imaginist.com/reference/tbl_graph.html">Tidygraph is basically a wrapper for igraph</a>, so all the igraph functions work with Tidygraph objects. tbl_graph is just a way of integrating igraph into the functionalities of the tidyverse. For example, igraph’s degree function works just the same:</p><pre>degree(as_tbl_graph(df))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*yqthKpvu_8QBXMRR2e1amw.png" /><figcaption>igraph’s Degree function output on the Tidygraph marvel data</figcaption></figure><p>We can find the node with the largest <a href="https://visiblenetworklabs.com/2021/04/16/understanding-network-centrality/">betweenness centrality</a> using a combination of Tidygraph and dplyr function:</p><pre>marvel_network_centrality &lt;- marvel_network %&gt;%<br>  activate(nodes) %&gt;%<br>  mutate(&quot;centrality&quot; = centrality_betweenness()) %&gt;%<br>  arrange(desc(centrality)) %&gt;% # order from greatest to least centrality<br>  data.frame() # returns a dataframe instead of a tbl_graph object</pre><pre>&gt; marvel_network_centrality<br>                    name  centrality<br>1   SPIDER-MAN/PETER PAR 4551779.738<br>2        CAPTAIN AMERICA 3375281.169<br>3   IRON MAN/TONY STARK  1923899.517<br>4       WOLVERINE/LOGAN  1840845.291<br>5    HAVOK/ALEX SUMMERS  1468698.666</pre><p>Spiderman is the most central superhero in the sense that he is along the most shortest paths between any other two heroes, followed by Captain America and Iron Man.</p><p>Tidygraph is a wrapper for igraph, and can do all the same visualization functions that come with igraph. Additionally, the <a href="http://exts.ggplot2.tidyverse.org/ggraph.html">ggraph package</a> can visualize Tidygraph objects, opening the door for more customization options.</p><p>I recommend those interested in Tidygraph to check out <a href="https://medium.com/slalom-technology/an-intro-to-graph-theory-and-analysis-using-tidygraph-d5199490963">this article by Joshua Limaye</a> to learn more.</p><h3>Network Visualization</h3><h4><a href="https://datastorm-open.github.io/visNetwork/">(R) visNetwork</a></h4><p>If you want to create interactive visualizations where you can drag nodes around and look at graphs from different perspectives, then visNetwork is the package for you. Based on the javascript library by the same name, visNetwork integrates the interactivity of javascript into R, creating beautiful, interactive visualizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynlK5ejTnph4ij3bn_798A.png" /></figure><p>visNetwork is NOT a network analysis tool, but exclusively used for network visualization.</p><p>Especially when paired with igraph, visNetwork is easy to begin using. However, it can be harder to find answers to more specific, customization problems given the at times lacking documentation. Here’s how to make a visNetwork visualization from our igraph network object we created earlier:</p><pre>library(visNetwork)<br>marvel_sample &lt;- df %&gt;%<br>  slice_sample(n = 100) # only plot some data to save processing time<br>marvel_sample_igraph &lt;- graph_from_data_frame(marvel_sample) # create igraph obj<br>visIgraph(marvel_sample_igraph) # plot visNetwork<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*_V5F5kIQ-0iSsrHixjVfmg.png" /><figcaption>visNetwork output of Marvel Network data</figcaption></figure><p>This is just the tip of the iceberg when it comes to visNetwork. For more information, check out the <a href="https://datastorm-open.github.io/visNetwork/">docs</a>, and the variety of stack overflow questions that have been answered to teach others how to use the package.</p><h3>Network Statistics</h3><h4>(R) The Statnet packages — network, sna, ergm</h4><p>For the more experienced statisticians looking to perform randomization tests on their network data, the <a href="https://statnet.org/packages/">statnet packages </a>are your one-stop-shop. These use network objects as their jumping off point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*JnJt843uX-srhMnnUngFag.png" /></figure><pre>library(network)<br>colnames(df) &lt;- c(&quot;from&quot;, &quot;to&quot;) # network needs the edgelist to have these column names<br>marvel_network &lt;- as.network(df,<br>  loops = TRUE, # contains cycles<br>  multiple = TRUE # contains repeat edges<br>)</pre><pre>&gt; as.network(df, loops = TRUE, multiple = TRUE)<br> Network attributes:<br>  vertices = 6426 <br>  directed = TRUE <br>  hyper = FALSE <br>  loops = TRUE <br>  multiple = TRUE <br>  bipartite = FALSE <br>  total edges= 574467 <br>    missing edges= 0 <br>    non-missing edges= 574467 <br><br> Vertex attribute names: <br>    vertex.names <br><br> Edge attribute names not shown </pre><p>Here’s an example that calculates the number of dyads (two-node cycles) in the data:</p><pre>network.dyadcount(marvel_network)<br>[1] 41293476</pre><p>I can go into the details of using the statnet packages in a future post, and explain how its randomization tests can expand your network analysis toolset. Until then, the author’s published a <a href="https://www.jstatsoft.org/article/view/v024i09">detailed description of their packages in the Journal of Statistical Software</a> that is a great resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*km8IVOCT9OzdVBw6" /><figcaption>Photo by <a href="https://unsplash.com/@wacalke?utm_source=medium&amp;utm_medium=referral">Mateusz Wacławek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Closing Thoughts</h3><p>There’s a tool for just about every problem out there, and it’s the same case for network analysis in Python and R. NetworkX is my favorite all-around network analysis and visualization package, with igraph close behind. I’m just starting to play around with Tidygraph and am enjoying its integration with dplyr. visNetwork is the absolute best for interactivity, and is what I recommend for visualizing networks in Shiny apps. Finally, the statnet network package is a solid base for more randomization-based analyses.</p><p>Give a like, follow, and check out my profile for more programming tutorials and takes. I’ve written a few articles so far about data science and am planning to incorporate topics from civil engineering and my research in fuzzy cognitive maps and interdisciplinary problem-solving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=800bfe412700" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[R vs Python? More like R AND Python!]]></title>
            <link>https://medium.com/@ben.roston/r-vs-python-more-like-r-and-python-4f015fa57b6a?source=rss-43d56b97a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f015fa57b6a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[reticulate]]></category>
            <dc:creator><![CDATA[Ben Roston]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 22:21:19 GMT</pubDate>
            <atom:updated>2024-02-29T15:50:34.662Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JbNTx-BtfQlthk3h" /><figcaption>Photo by <a href="https://unsplash.com/@haiiimam?utm_source=medium&amp;utm_medium=referral">Imam Fadly</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Programming languages are tools, and like tools, no individual programming language is best suited for every problem. Sure, a screwdriver could get a nail into a wall, but what about a hammer? Data science, much like home improvement projects, is better when we approach it with a diverse toolbox at our disposal.</p><p>There is a literature’s worth of debate about which language is better. R is an absolute power-house for statistics and Python has the benefits of being a more general-use language. For a majority of problems, though, it is less about the actual programming language and more about the libraries and packages available to that particular language.</p><p>R’s Tidyverse suite streamlines dataframe wrangling through its line-by-line piping mechanic. Python’s Pandas library handles dataframes, taking on a more object-oriented approach. Ultimately, though, both the Tidyverse and Pandas (along with other core Python libraries like numpy) can perform fairly similar functions. However, not every tool has a twin across languages, and even dplyr and pandas have their differences.</p><p>What if you are hundreds of lines into a project in R and realize you need a function from a Python library to solve your latest problem? What if you need to write an analysis in Python, but want to visualize it using R’s ggplot2 library?</p><p>I ran into this problem recently while setting up a network analysis project in R, but none of the native libraries quite did what I needed as well as Python’s NetworkX library. Luckily, the folks at Posit (previously RStudio) are here to help with the <a href="https://rstudio.github.io/reticulate/"><strong>Reticulate</strong> package</a>.</p><p>Reticulate means to form a network or connections. The Reticulate package establishes a connection between R and Python that vastly increases the problem-solving tools available to data scientists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fIod7H5-YBM9O8Rl" /><figcaption>R and Python, Best Friends. Photo by <a href="https://unsplash.com/@joshua2529?utm_source=medium&amp;utm_medium=referral">Joshua Clay</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Getting Started with Reticulate</h3><p>Before we can begin using Python in R, we need to do some setup. First, both R and Python need to be installed. The reticulate package will automatically use the Python version in the system PATH, but you can manually select a Python version, too. For more info, see the <a href="https://rstudio.github.io/reticulate/articles/python_packages.html">Reticulate Getting Started page.</a></p><p><em>Note: Since the Reticulate package is an R package, we have to bring Python into R.</em></p><p>Like all packages in R, we begin with the combo:</p><pre># install and load the reticulate package<br>install.packages(&quot;reticulate&quot;) # install from CRAN<br>library(reticulate) # load the reticulate package</pre><p>To install Python packages, we use the function py_install() . Reticulate automatically creates a default environment called “r-reticulate” where it installs Python packages from pip. For example:</p><pre>py_install(&quot;pandas&quot;)</pre><p>There is functionality to interface Reticulate with Conda and Virtualenv. For more info, see the <a href="https://rstudio.github.io/reticulate/articles/python_packages.html">package installation help page.</a></p><p>Now, when we load a Python library into R it works a little differently that a simple call to the library() function. Instead, we call Reticulate’s import function. Let’s try it out:</p><pre>import(&quot;pandas&quot;) # Reticulate loads pandas from the virtual environment<br><br># Which returns<br>Module(pandas)</pre><p>What is going on with that Module(pandas) object? When we call library() all of the functions within the package get loaded into the namespace so we have access to them. Calling import() does the same thing, but stores all the functions into this Module() object. So, how do we access the actual Python functions? We create a variable to store the Module in that we can then access later.</p><pre>pandas &lt;- import(&quot;pandas&quot;) # Load Module(pandas) into its own variable</pre><p>Okay, but now we need to access the functions within the pandas variable. We’ll use the same $ convention used in R data.frames. For example, to use Pandas’ read_csv() function, we would write:</p><pre>pandas$read_csv(&#39;path/to/file.csv&#39;)</pre><p>Let’s look at an example and try to take a dataframe in r and perform some functions in pandas in the same script. We’ll use the classic mtcars dataset.</p><pre>                   mpg cyl disp  hp drat    wt  qsec vs am gear carb<br>Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4<br>Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4<br>Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1<br>Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1<br>Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2<br>Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1</pre><p>Say we want to create a pivot table of the dataset that shows how mpg varies with the number of cylinders ( cyl ) and gears( gear ). I can get the jist of the data using dplyr:</p><pre>library(dplyr)<br>mtcars %&gt;% <br>  group_by(cyl, gear) %&gt;%<br>  summarize(mean = mean(mpg))</pre><pre>Output<br># A tibble: 8 × 3<br># Groups:   cyl [3]<br>    cyl  gear  mean<br>  &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;<br>1     4     3  21.5<br>2     4     4  26.9<br>3     4     5  28.2<br>4     6     3  19.8<br>5     6     4  19.8<br>6     6     5  19.7<br>7     8     3  15.0<br>8     8     5  15.4</pre><p>That looks great, but the relationship between the three variables is not quite obvious. What we really need is a pivot table, and the dplyr library can’t help us there. Instead of moving our analysis over to Python, we can bring Python into R!</p><pre>pandas &lt;- import(&quot;pandas&quot;)<br>numpy &lt;- import(&quot;numpy&quot;) # use py_install(&quot;numpy&quot;) to install<br><br>df &lt;- pandas$pivot_table(<br>  mtcars,<br>  values=&#39;mpg&#39;,<br>  index=&#39;gear&#39;,<br>  columns=&#39;cyl&#39;,<br>  aggfunc=numpy$sum # notice the call to the numpy module to use the Python sum function<br>)</pre><pre>Output<br>    4.0  6.0   8.0<br>3  21.5 39.5 180.6<br>4 215.4 79.0   NaN<br>5  56.4 19.7  30.8</pre><h3>Source Python Scripts in R</h3><p>Beyond importing packages to use in R, we can actually import individual scripts into R, too! Instead of import() , we use the source_python() function to load individual python scripts as Module objects.</p><pre>source_python(&#39;path/to/script.py&#39;)</pre><p><em>Note: Manually setting the working directory is not recommended. It’s to use the total filepath from either a) the system’s base library (C:, Macintosh HD, Onedrive, etc.) or b) the project’s directory (identify files in directory with list.files()).</em></p><p>Interestingly, source_python() loads functions within the given script into the global environment in R rather than loading into a module. In other words, we don’t need to define a variable to load our python functions into when sourcing from custom scripts.</p><p>Say we have a python file called addition.py that takes the sum of two values:</p><pre># addition.py<br>def add(num1, num2):<br>    numSum = num1 + num2<br>    return(numSum)</pre><p>We can then call our custom Python script into R. For example, let’s say an R script defines two numbers, and then calls our Python script to sum them together. Here’s how it looks:</p><pre>first_number &lt;- 100<br>second_number &lt;- 200<br><br># load custom python script&#39;s add function into the global environment<br>source_python(&quot;addition.py&quot;) <br><br># call the add function<br>add(first_number, second_number)</pre><p>Reticulate translated our add function from Python into an R function. The same functionality works for Python scripts with multiple functions as well.</p><p>The great divide between R and Python has been resolved, not by an emergent victor, but by the ability to combine the strengths of both! The Reticulate package is absolutely worth diving into for anyone starting their Data Science journey and those well along their path. It is nothing short of a game-changer.</p><p>Check out the <a href="https://rstudio.github.io/reticulate/articles/python_packages.html">Reticulate website</a> for more information. It’s a little dense at points, so feel free to share if you have any questions getting started with the package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RN6u5FLrP7wFiR6Q" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Give a like, follow, and check out my profile for more programming tutorials and takes. I’m hoping to get out one article per week over the next few months. So far I’ve written mainly about data science, and will likely tackle some topics related to Civil Engineering in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f015fa57b6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What makes R Shiny feel so intimidating?]]></title>
            <link>https://medium.com/@ben.roston/what-makes-r-shiny-feel-so-intimidating-ec1f02147d77?source=rss-43d56b97a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec1f02147d77</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[shiny]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Ben Roston]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 02:44:48 GMT</pubDate>
            <atom:updated>2024-02-29T15:50:20.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*JrHCvwZ6oBE3LmdQRK4sbQ.jpeg" /></figure><p>Code is, at its core, a way of communicating with a computer. But, computer’s speak in 1’s and 0’s and not Medium articles so we need some way to translate something we understand to something the computer understand. The difference between interpreted and compiled languages is in how they tackle this human-computer language gap.</p><h4><em>“What makes R Shiny feel so dissonant for even experienced R programmers is that R is an interpreted language, but R Shiny works more like a compiled language.”</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*GrupdFCbT57GxM3lYyXjYw.png" /></figure><p>We can imagine working in an interpretive language like having our own personal translator. In our conversations with the computer, the translator repeats what we say sentence-by-sentence into a language the computer understands. An interpreter can read our code line-by-line. If I wanted to tell the computer to print, “Hello, World!” I just need to hit “run” for the interpreter to translate everything to the computer and have the computer return every programmer’s first words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WsLZRBNNSK3Ces5gs013vg.jpeg" /></figure><p>The key thing to remember, here, is <strong>line-by-line</strong>. Interpreters let you run your code as you go, in bite size chunks to track everything going on in your program as you go. Languages like R and Python work this way, where we can run some code, check out some variables, run some more code, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ak8VoUltaHrQD5fv_9BTog.png" /></figure><p>Where interpretive languages are like having a personal translator, compiled languages are like having a personal publisher. Publishers want the whole book before translating it into another language and sending it off to a new audience. Compiled languages use a compiler to “publish” our code into an executable (.exe file) that a computer reads like a book. Take the classic “Hello, World!” example. We write up the code and then compile the entire script into an executable. Then, to see those two magical words, we simply run the newly created executable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*PBCzmq1BCyi3sOBViK7Dug.gif" /></figure><p>The big thing here is that <strong>we can’t edit code within an executable!</strong> If we want to change our code, we need to change the original script, re-compile it, and the run the new executable. When working with compiled languages like C, we write some code, compile it, check out the executable, then edit the code, re-compile it, and check out the new executable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KO6KhaWei-R5EwNUMk0y3g.png" /></figure><p>What makes R Shiny feel so dissonant for even experienced R programmers is that R is an interpreted language, but R Shiny works more like a compiled language.</p><p>To dive deeper into what it means for an interpreted language to behave like a compiled language, let’s look at a quick example of a Shiny app that prints “Hello, World!”</p><pre>ui &lt;- fluidPage(<br>  print(&quot;Hello, World!&quot;)<br>)<br><br>server &lt;- function(input, output, session) {<br>  # empty for this example<br>}<br><br># Call the ui and the server function to run the Shiny App<br>shinyApp(ui, server)</pre><p>Every Shiny app is composed of a ui (User-Interface) and a server. The ui describes what the user sees while the server handles all the (back-end) calculations where all the data-science-y bits go. The code above creates the basic page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*9SIzYvnvc6dxe8DWTRViNw.png" /><figcaption>Screenshot of “Hello, World!” Shiny App. That number in the top-right is the IP address of our app which will always begin with 127.0.0.1. That’s the IP address our computers use to create a web page hosted exclusively locally which means our app is not connected to the internet. Until we get into publishing, all our apps will be hosted at the 127.0.0.1 IP address.</figcaption></figure><p>That shinyApp(ui, server) line at the bottom “compiles” the ui and server function, and then “publishes” the executable which produces our “Hello, World!” web page. Notice how you can’t edit the text within the App. Shiny Apps work like any ordinary web page where you can’t change anything, you can only highlight text. This is the compiled language behavior at-play. If we want to change our app to say, “Hello, Galaxy!” we need to close out the “Hello, World!” version, change the source code, and then re-“compile” our App.</p><pre>ui &lt;- fluidPage(<br>  print(&quot;Hello, Galaxy!&quot;) # Changed greeting to the Galaxy<br>)<br><br>server &lt;- function(input, output, session) {<br>  # empty for this example<br>}<br><br># Call the ui and the server function to run the Shiny App<br>shinyApp(ui, server)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*p0IfGGU1UwSGmxYS04h3GQ.png" /><figcaption>Note: The ui is a variable while the server is a function. Why aren’t both functions? The ui is just a window into what is going on inside the app. The ui defines what the server function takes in and sends back to the user. The server is a function whose behavior is influenced by the ui variable.</figcaption></figure><p>This subtle change to the R workflow has a big impact on the way we interact with our programs. Next, let’s consider an example app that adds two numbers and outputs their sum. In a typical R script, the program looks like:</p><pre>number1 &lt;- 10<br>number2 &lt;- 20<br><br>sum_of_numbers &lt;- number1 + number2<br><br>print(sum_of_numbers)</pre><p>Consider how the variables number1 , number2 , and sum_of_numbers are global variables. When we run each line, the interpreter adds the variables to the Global Environment, which we can access in the console and view in the RStudio IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1_ARS56zbsALDLjXkABaA.png" /></figure><p>The Shiny version of our number adding program takes advantage of both the ui and the server function. Here is one way to write our app:</p><pre>ui &lt;- fluidPage(<br>  # verbatimTextOutput = print() Show how it would in the console<br>  verbatimTextOutput(&quot;sum_of_numbers&quot;)<br>  # creates a variable &quot;sum_of_numbers&quot; as an output<br>  # accessed via output$sum_of_numbers<br>)<br><br>server &lt;- function(input, output, session) {<br>  number1 &lt;- 10<br>  number2 &lt;- 20<br><br>  sum_of_numbers &lt;- number1 + number2<br><br>  output$sum_of_numbers &lt;- renderPrint(sum_of_numbers)<br>  # can be read as:<br>  # for the sum_of_numbers output, print(sum_of_numbers)<br><br>  # renderPrint in the server is paired with verbatimTextOutput in the ui<br>}<br><br># Call the ui and the server function to run the Shiny App<br>shinyApp(ui, server)</pre><p>There’s more going on here now that our app has to perform a calculation in the server. Let’s break it down!</p><p>The ui variable declares an output called sum_of_numbers that shows the console output of the variable as if we called print(sum_of_numbers) . Beyond that funky output line, the server function is pretty busy. We define fixed variables (number1 &lt;- 10 and number2 &lt;- 20) along with a calculation based on those variables (sum_of_numbers &lt;- number1 + number2 ). Classic, interpretive R. We tell the server to output that calculation to the ui to close out the server function. Finally, the shinyApp call “compiles” the ui variable and server function to produce this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*m376AImIHAxoCIlKBvZ-kQ.png" /></figure><p>Let’s say we want find the sum of different numbers? Like the “Hello, World!” example, we need to close the app, then edit the code, and re-compile it to produce a different sum. What’s more, beyond the variable declarations in the code, we have no way of seeing what values our variables hold. It’s not like in an interpretive language where, while the app is running, we can access the variables in the command line or eyeball them in RStudio’s global environment pane. Like in compiled languages, once shinyApp is called, it runs the executable, and we don’t get to play with executables in the same way we get to play with our interpreted R scripts.</p><p>That’s the crux of it. We don’t get to play with executables in the same way we get to play with interpretive language scripts. That’s what makes R Shiny feel so intimidating. It’s an entire new way of programming, of thinking, of problem-solving!</p><p>I plan to publish more articles in the future walking through how we work through this new paradigm throughout Shiny App development, and more! In the meantime, be sure to check out the Shiny cheat sheet <strong>(</strong><a href="https://raw.githubusercontent.com/rstudio/cheatsheets/main/shiny.pdf">https://raw.githubusercontent.com/rstudio/cheatsheets/main/shiny.pdf</a><strong>) </strong>or the Mastering Shiny text (<a href="https://mastering-shiny.org/index.html">https://mastering-shiny.org/index.html</a>) for more info about the nuances of Shiny and everything that comes with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec1f02147d77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing Manim via Conda (Windows and MacOS)]]></title>
            <link>https://medium.com/@ben.roston/manim-installation-via-conda-windows-and-macos-9db35a99311a?source=rss-43d56b97a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9db35a99311a</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[manim]]></category>
            <dc:creator><![CDATA[Ben Roston]]></dc:creator>
            <pubDate>Mon, 26 Sep 2022 23:52:02 GMT</pubDate>
            <atom:updated>2022-09-26T23:54:22.822Z</atom:updated>
            <content:encoded><![CDATA[<p>Updated: 9/26/2022</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*zqrBXOUDblnrU6vq9S6I1g.png" /><figcaption>Logo from the 3Blue1Brown version <a href="https://github.com/3b1b/manim">https://github.com/3b1b/manim</a></figcaption></figure><p>For those inspired by the wonderful videos of <a href="https://www.youtube.com/c/3blue1brown">3Blue1Brown</a> to start making your own math animations or static visualizations then you have likely come across the Manim package for python.</p><p>There are a few versions of manim floating around and it can be unclear at first which one you should use. There’s <a href="https://github.com/3b1b/manim"><strong>manimgl</strong></a> which is the one used in 3Blue1Brown videos and then there’s the <a href="https://github.com/ManimCommunity/manim/"><strong>Community Edition</strong></a> which is a fork of the original. Most sources point newcomers toward the Community Edition, so that’s the one we’ll check out here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Y0-d27l96TaUDY3syoOUcg.png" /><figcaption>Logo from the Community Edition <a href="https://github.com/ManimCommunity/manim/">https://github.com/ManimCommunity/manim/</a></figcaption></figure><p>Documentation for the Community Edition can be found <a href="https://docs.manim.community/en/stable/index.html"><strong>here</strong></a><strong> </strong>and it also has a corresponding Github repository <a href="https://github.com/ManimCommunity/manim/"><strong>here</strong></a>. There are not conda-specific installation instructions in the Community Edition’s docs, but there are instructions on installing the manimgl version over on its <a href="https://3b1b.github.io/manim/getting_started/installation.html">doc site</a>. However, these instructions described how to clone the manimgl github repo into a conda environment rather than installing the package via <em>pip. </em>Ultimately, I was able to install the community edition through conda using a combination of the docs from the original and community edition, an afternoon of frantic google searches, and a foyer into the depths of stackoverflow. Here’s what ended up working for me.</p><h3>Create a Conda Environment with Python</h3><p>The docs recommend creating the conda environment with python using the following code:</p><pre>conda create -n manim python<br>conda activate manim</pre><h3>Install Manim and its Dependencies</h3><p>We need to install a few dependencies before we get to manim, mainly FFmpeg and a LaTeX distribution. For Windows, I recommend using <a href="https://chocolatey.org/install">Chocolatey</a>, and for MacOS, I recommend installing these via <a href="https://brew.sh/">Homebrew</a>.</p><h4>Windows — Chocolatey</h4><p>Open an Anaconda prompt <strong>as an administrator</strong>. Then, to install manim through Chocolatey, run:</p><pre>choco install manimce</pre><p>This might take a few minutes, and will likely request a reboot once it is finished.</p><p>Note: FFmpeg, a package discussed in the MacOS section is automatically downloaded when installing manim through Chocolatey, so no need to explicitly install it here.</p><p>Now, we need a LeTeX distribution. Through Chocolatey, there is a LaTeX add-on (so-to-speak) that can be installed AFTER manim is installed. Here’s the command to run once manim is downloaded (again, the Anaconda Prompt needs to be running <strong>as an administrator</strong>):</p><pre>choco install manim-latex</pre><p>Finally, install manim using pip:</p><pre>pip install manim</pre><p>All set, check out the next section to start using manim!</p><h4>MacOS — Homebrew</h4><p>FFmpeg is NOT automatically downloaded with manim in MacOS. Download it and cairo through homebrew:</p><pre>brew install py3cairo ffmpeg</pre><p>From the docs: “On <em>Apple Silicon</em> based machines (i.e., devices with the M1 chip or similar; if you are unsure which processor you have check by opening the Apple menu, select <em>About This Mac</em> and check the entry next to <em>Chip</em>), some additional dependencies are required, namely:”</p><pre>brew install pango scipy</pre><p>If you want to use LaTex, the docs recommend using MacTeX which can be installed using the code below. Warning: this takes 4GB of space and may take a while to download.</p><pre>brew install --cask mactex-no-gui</pre><p><strong>FOR MAC OS</strong>… I got an error in the terminal later in the installation process that said “Unknown encoder ‘libx264.” I think this has something to do with the way ffmpeg is installed and everything worked when I ran the following code PRIOR to installing manim (make sure manim env is activated):</p><pre>conda install x264==&#39;1!152.20180717&#39; ffmpeg=4.0.2 -c conda-forge</pre><p><a href="https://stackoverflow.com/questions/9764740/unknown-encoder-libx264/58421346#58421346">https://stackoverflow.com/questions/9764740/unknown-encoder-libx264/58421346#58421346</a> — Look for the answer by Shital Shah</p><p>Finally, install manim using pip:</p><pre>pip install manim</pre><p>All set, check out the next section to start using manim!</p><h3>Try using Manim</h3><p>This section summarizes parts of the <a href="https://docs.manim.community/en/stable/tutorials/quickstart.html">Quickstart</a> page on the Manim Community site with additions throughout that helped me when getting started for the first time. Note: I’ll be using VS Code for this walkthrough.</p><h4>Create a project folder</h4><p>Create a new folder somewhere on your computer and name it something like “getting_started_w_manim”. Open VS Code and Open it to the newly-created folder.</p><p>Then, create a python script within the “getting_started_w_manim” folder we just created, and call it “create_circle.py”</p><h4>Opening the “manim” conda env in VS Code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*7LRZEQRfhGYdBdi5jRg5zA.png" /></figure><p>Next, select the python interpreter in the conda environment that has manim installed. Open the Command Palette by holding Ctrl + Shif + P for Windows or Cmd + Shift + P for MacOS (the Command Palette can also be opened from the View tab).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4DdfbCNXnB72T2D-SVJ5w.png" /></figure><p>With the Command Palette open, type “Python: Select Interpreter” into the search bar and select it in the drop-down. This will display a list of interpreters that VS Code can find on your computer. Somewhere down the list in the “Conda” section, find the “manim” environment (it’ll look something like Python 3.8.13 (‘manim’) and select it. To confirm the change in environment, make sure you see something like (‘manim’: conda) in the bottom right of VS Code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*i7FzKYMjq0CNngDGndVXog.png" /></figure><h4>Writing our First Manim Script</h4><p>Before writing into the script, check to ensure it has access to manim. Open a python terminal and run:</p><pre>from manim import *</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xnTWuDlTCQYv89QSVpxFQ.png" /></figure><p>If this runs, everything is good to go. If not, … check the error messages, try the steps above again, check stackoverflow, check the docs, anything that might help.</p><p>The Quickstart guide provides this sample code to implement in our first script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*G8Y3fdR-G_-xZ67ntUP9Ug.png" /><figcaption>From the docs: <a href="https://docs.manim.community/en/stable/tutorials/quickstart.html">https://docs.manim.community/en/stable/tutorials/quickstart.html</a></figcaption></figure><p>Here’s a copy-and-paste-able version of the same code:</p><pre>from manim import *</pre><pre>class CreateCircle(Scene):<br>    def construct(self):<br>        circle = Circle()<br>        circle.set_fill(PINK, opacity=0.5)<br>        self.play(Create(circle)) </pre><p>Go ahead and run this and make sure that there are no errors.</p><p>Notice how no fancy animation pops up? That’s because we need to call the CreateCircle scene from the command prompt/terminal with:</p><pre>manim create_circle.py CreateCircle</pre><p>… this might pop-up with an error saying “There are no scenes inside that module.” That’s okay!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLmilJE5s7xEmKF7SkmadQ.png" /></figure><p>Manim needs us to save our scripts before calling the scenes within them. Save the script and try the previous command again.</p><p>If successful, a “media” directory will pop-up within the “getting_started_w_manim” folder. It has “images” and “videos” sub-directories. Our animation can be found under “videos,” and there it is! CreateCircle.mp4!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*kOGkW2SHwEiu916C5VOkNw.png" /></figure><p>You’ll have to open the .mp4 file outside of VS Code, so just navigate to its location, double-click and watch your animation come to life :)</p><p>To learn how to use manim once it’s installed, I recommend starting with the <a href="https://docs.manim.community/en/stable/index.html#">Manim Community site</a> and its <a href="https://github.com/ManimCommunity/manim/">Github page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9db35a99311a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should try making your own R Package]]></title>
            <link>https://medium.com/@ben.roston/why-you-should-try-making-your-own-r-package-2f22e4534c03?source=rss-43d56b97a3c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f22e4534c03</guid>
            <category><![CDATA[rstudio]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[development-packages]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ben Roston]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 17:29:03 GMT</pubDate>
            <atom:updated>2024-02-29T15:50:02.190Z</atom:updated>
            <content:encoded><![CDATA[<p><em>No, really! If you have any experience working with Projects in RStudio or simply understand how to work with functions in R, then creating a Package will be a great way to upgrade your workflow. Package development is so accessible and streamlined in RStudio that it may even be your go-to for future projects.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TH-cdGWQ6IaFRwt1scaG3Q.png" /></figure><p>Why make a full-blown Package when working within RStudio Projects is already a great experience? First, a Package is not a replacement for a Project, but a way to improve how you functions interact within a Project. Projects can require 10’s to 100’s of user-defined functions that can be hard to keep track of, access, and even just read when called altogether in the Main script. The idea is that functions written within a package can be called within a larger project. There are a few reasons why this seemingly “extra step” can actually be a big help for overall projects: 1) Directory Management, 2) Testing Capability, and 3) Documentation. Let’s walk through each of them.</p><ol><li><strong>Directory Management:</strong><br>In Projects, it’s typical to have a “main” script that calls all the functions defined in scripts written elsewhere in some directory. The code below gives an example of how this usually works.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/381e530525e38d1e476ccbf4a298c2c0/href">https://medium.com/media/381e530525e38d1e476ccbf4a298c2c0/href</a></iframe><p>Although great for projects with minimal user-defined functions, this can quickly get out of hand for those with many such functions. If functions are written across multiple scripts, then each of those scripts will have to be called with the “source” function. If, say, each new function gets its own script for readability purposes, then every single function will need to be “sourced” in the “main” script. That’s a lot of repetition, a lot of function_paths to define, and really it’s a needlessly long way of doing what library(some_package) does innately.</p><p><strong>2. Testing Capability<br></strong>Functions need to be tested to ensure they do what they need to be doing. Similar to Roxygen Skeletons, there is a standardized way to test functions within Packages. Unlike Roxygen Skeletons, tests need to be written within packages, and will look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0492125fda7f5fcf505cd382ad82abe2/href">https://medium.com/media/0492125fda7f5fcf505cd382ad82abe2/href</a></iframe><p>test_that is a boolean that returns either TRUE or FALSE and essentially asks “Does the function do the thing?” Tests can be simple like the example or complex. They have depth, yet are genuinely accessible to use. Tests can significantly help with debugging and can even make sure some of the most brain-aching bugs never even make their way into your outputs.</p><p><strong>3. Documentation</strong><br>Functions need good documentation, period. When describing functions in projects though, it’s hard to know exactly what a description should include:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a817eac72c770f974c55b0379fd2ab1/href">https://medium.com/media/1a817eac72c770f974c55b0379fd2ab1/href</a></iframe><p>Luckily, RStudio has a built-in tool called “Roxygen Skeletons” to help with function documentation. These can be used with any function and are a great way to start standardizing aspects of your scripts. Here’s what one looks like with our example function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/974749bf9b82138249b43085a60a95c1/href">https://medium.com/media/974749bf9b82138249b43085a60a95c1/href</a></iframe><p>To add a Roxygen description, start by placing the cursor anywhere inside the function definition. In the banner with File, Edit, Code, etc. click on “Code” to display a lengthy drop-down menu. Towards the middle, find “Insert Roxygen Skeleton” and select it. The function should now be preceded by lines starting with #’ that can now be filled in.</p><p>Notice how the skeleton automatically includes places to describe each of inputs ( @param ). That’s just one of the ways Roxygen makes documentation more straightforward.</p><p>Let’s see what our example skeleton looks like when it’s all filled in:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d157ea6d5938e850151467f0ae2d279f/href">https://medium.com/media/d157ea6d5938e850151467f0ae2d279f/href</a></iframe><p>Breaking it down, “Title” was replaced with the actual title of the function (which should be more plain-language than the function name). There are now brief descriptions after the first and second inputs, and there’s an additional description that shares what the function returns. The skeleton ends with an example showing how the function can be used. export is a bit more specific to Packages specifically and we’ll circle back to it later.</p><p>Since Roxygen Skeletons are so standardized, it is easy for RStudio’s Package development workflow to create clean function documentation not dissimilar from those you’ll find on CRAN! Not only do these skeletons help improve readability, but also present a big step toward the improved code-sharing that make Packages so powerful.</p><p><strong>Closing Thoughts</strong></p><p>Package Development is a great way to learn more of the intermediate elements of R and RStudio while also improving the overall development process. For more information about Package Development and its actual implementation in broader Projects, check out <strong>R Packages </strong>by Hadley Wickham and Jenny Bryan (two excellent authors with a ton of great FREE resources on R and RStudio). For a detailed overview of the Package Development workflow from start to finish, check out the second chapter, “The Whole Game,” here: <a href="https://r-pkgs.org/Whole-game.html">https://r-pkgs.org/Whole-game.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f22e4534c03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>