<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Julia Piaskowski</title>
<link>https://jpiaskowski.gitlab.io/posts.html</link>
<atom:link href="https://jpiaskowski.gitlab.io/posts.xml" rel="self" type="application/rss+xml"/>
<description></description>
<generator>quarto-1.6.40</generator>
<lastBuildDate>Fri, 16 Oct 2026 17:50:02 GMT</lastBuildDate>
<item>
  <title>Jane Vandal: There is No Ghost in the Shell</title>
  <link>https://jpiaskowski.gitlab.io/posts/humanizing-chatbots/</link>
  <description><![CDATA[ 




<p><img src="https://jpiaskowski.gitlab.io/posts/humanizing-chatbots/featured.jpg" class="img-fluid"> <em>Image: <a href="https://publicdomainreview.org/collection/march-of-the-intellect/">Ghost in the Shell</a>, Dir. Mamoru Oshii, 1996</em></p>
<blockquote class="blockquote">
<p>Repeated, personalised interactions can contribute to a sense of emotional closeness to AI that mirrors interpersonal relationships. —<a href="https://www.sciencedirect.com/science/article/pii/S2949882126000757">Hung et al (2026)</a></p>
</blockquote>
<div class="cell page-columns page-full" data-layout-align="center">

<div class="no-row-height column-margin column-container"><div class="cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://jpiaskowski.gitlab.io/posts/humanizing-chatbots/jane_vandal.png" class="img-fluid figure-img"></p>
<figcaption>Jane Vandal</figcaption>
</figure>
</div>
</div></div></div>
<p>The University of Idaho has recently released its own chatbot “Jane Vandal”, complete with a cartoon avatar of a brunette woman and some <a href="https://www.uidaho.edu/people/jane">sensible guidelines</a> for usage.</p>
<p>While I understand the motivation build a specialized information fetching tool serving specific interests, I question why we choose to gender<sup>1</sup>, name, and anthropomorphize a chatbot at all given the harm associated with this. A chatbot is a large language model built on deep learning architecture that–after being trained on a large body of text–is reasonably good at predicting the most statistically likely words that should follow a prompt or question. It is a set of mathematical weights and functions. It is not a person, nor is it conscious. <sup>2</sup></p>
<div class="no-row-height column-margin column-container"><div id="fn1"><p><sup>1</sup>&nbsp;I do appreciate the intentions behind creating a foil to Joe Vandal, the male-presenting University of Idaho Mascot, and providing female representation. Nevertheless, it’s hard to miss the gender signalling in making our helpful assistance female. After I offload some menial tasks on her, I hope she can also fetch me coffee.</p></div><div id="fn2"><p><sup>2</sup>&nbsp;If you have time to read Ted Chiang’s 10,000-word <a href="https://www.theatlantic.com/philosophy/2026/06/no-artificial-intelligence-is-not-conscious/687378/">essay</a> on why AI is not conscious, it is a comprehensive exploration of these arguments, revealing how insubstantial they are.</p></div></div><p>We all know this (I hope!), but when interacting with a chatbot that calls itself “I”, apologizes when called out, and responds sympathetically to us, it’s easy to convince ourselves that a <a href="https://www.sciencedirect.com/org/science/article/pii/S1066224326000055">chatbot understands us</a> like a human does (described as the “<a href="https://en.wikipedia.org/wiki/ELIZA_effect">ELIZA effect</a>”).</p>
<p>Many people have fallen into “relationships” with chatbots resulting in varying levels of harm. The most devastating outcomes are <a href="https://en.wikipedia.org/wiki/Deaths_linked_to_chatbots">suicides</a> (yes, in the plural).<sup>3</sup> People in mental distress have confessed their feelings of despair to chatbots. Chatbots have responded by confirming the user’s feelings, sometimes agreeing that the individual should commit suicide, helping write a goodbye note, and developing specific suicide plans. Given the seriousness of chatbot parasocial relationships, why is any institution continuing to anthropomorphize chatbots?</p>
<div class="no-row-height column-margin column-container"><div id="fn3"><p><sup>3</sup>&nbsp;In addition to the harm to individual users, companies can face substantial financial liability when their products result in this level of harm. <a href="https://finance.yahoo.com/technology/ai/articles/character-ai-files-bankruptcy-following-153859020.html">Character.ai has recently declared bankruptcy</a> in part to lawsuits from families after teen users committed suicide.</p></div></div><p>There is evidence that these parasocial relationships can range from detrimental to no effect at all, but I did not see much evidence indicating they were beneficial. It may be helpful to understand that anthropomorphized chatbots are a strategy to maximize user engagement and ensure a repeat customer base. It’s the same strategy behind social media clickbait and endless scrolling; <a href="https://link.springer.com/chapter/10.1007/978-3-031-61305-0_26">keep the user engaged</a> so they spend more time on the platform. I do not suspect that the creators of Jane Vandal had this in mind when they created her; more likely, they were following the template laid out by other generative AI-focused companies.</p>
<div class="callout callout-style-simple callout-note no-icon">
<div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon no-icon"></i>
</div>
<div class="callout-body-container">
<p>It is incredible to consider how we as a society continue to dehumanize out groups—-prisoners, undocumented immigrants, foreigners seeking entry to our country–-but are striving <a href="https://nymag.com/intelligencer/article/ai-artificial-intelligence-chatbots-emily-m-bender.html">to find sentience</a>, consciousness and possibly humanity in large language models. This feels like a side note, but it very much is the central issue. Dealing with sycophantic machines is easier than dealing with emotional, messy, imperfect humans. The temptation to humanize a chatbot and embrace that over actual people is a real concern, one that we ought to mitigate, not incentivize, however unintentionally.</p>
</div>
</div>
</div>
<p>This is not a terribly unique idea. Ted Chiang indicated in his <a href="https://www.theatlantic.com/philosophy/2026/06/no-artificial-intelligence-is-not-conscious/687378/">Atlantic essay</a> that having a chatbot use the pronoun “I” is inherently unethical since that action renews the impression that a chatbot is a person. The <a href="https://www.ap.org/the-definitive-source/announcements/ai-guidance-terms-added-to-ap-stylebook/">AP style book</a> now recommends that that reporters not anthropromorphize artificial intelligence systems:</p>
<blockquote class="blockquote">
<p>Artificial intelligence systems do not think, feel, want or understand. Avoid language that gives them human characteristics. This is called anthropomorphizing, when we ascribe human traits, emotions or behaviors to non-human things, such as animals or inanimate objects. Instead, explain what a system does, how well it performs, who built it and who could be affected by it. —Stylebook for the Associated Press</p>
</blockquote>
<p>It would be helpful to know what institutions are doing to limit the use of chatbots for parasocial relationships, and if there are strong guardrails to prevent egregious harms. When I told Jane Vandal that I was depressed, she did provide links to local mental health resources and indicated she was an “agent” lacking the depth of human feelings.<sup>4</sup> This is good! But, that message is contradicted when this tool is given a human name, human image and built to interact with us interpersonally. Most saliently, I hope we will depersonalize chatbots. Make them sources of information, not our friends. We can still have chatbots. They can be good at finding information. But let us not, as an individual or institution, pretend a chatbot is a person.</p>


<div class="no-row-height column-margin column-container"><div id="fn4"><p><sup>4</sup>&nbsp;A minor quibble, but while I understand what “agent” means in this context, many users may not. Jane Vandal is specifically marketed as “no code” implying no specialized knowledge of AI tools and jargon is needed to use it.</p></div></div>

 ]]></description>
  <guid>https://jpiaskowski.gitlab.io/posts/humanizing-chatbots/</guid>
  <pubDate>Fri, 16 Oct 2026 17:50:02 GMT</pubDate>
  <media:content url="https://jpiaskowski.gitlab.io/posts/humanizing-chatbots/featured.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Generative AI for Scientists: Helpful and Overhyped</title>
  <link>https://jpiaskowski.gitlab.io/posts/LLMs-utility/</link>
  <description><![CDATA[ 




<p><img src="https://jpiaskowski.gitlab.io/posts/LLMs-utility/featured.jpg" class="img-fluid"> <em>Image: Robert Seymour, <a href="https://publicdomainreview.org/collection/march-of-the-intellect/">March of the Intellect</a></em></p>
<p>I’ve been repeatedly asked to weigh in on how generative AI and its underlying architecture, large language models (LLMs)<img src="https://latex.codecogs.com/png.latex?%5E1"> can help scientists be more productive.</p>

<div class="no-row-height column-margin column-container"><div class="">
<p><img src="https://latex.codecogs.com/png.latex?1"> Sorry, I really hate acronyms, but “LLM” is used widely.</p>
</div></div><section id="useful-applications-of-llms" class="level2 page-columns page-full" data-number="1">
<h2 data-number="1" class="anchored" data-anchor-id="useful-applications-of-llms"><span class="header-section-number">1</span> Useful Applications of LLMs</h2>
<p>The best application of these tools seems to be to help amateurs do simple tasks in domains they have little knowledge and produce products that are reasonably good, albeit still with an amateur flavor. One example is video editing. I am terrible at this and do not attempt anything beyond clipping off the beginnings and ends of long videos and yet, this task takes ages, partly because I don’t know software landscape for video editing. There are AI tools that will transcribe the video (imperfectly, but still, not bad) and a user can directly edit that transcript to remove sections. No one is winning awards for production of my videos, but still, it gets the job done.</p>
<p>As a programmer, I found generative AI tools, with careful prompt engineering, can often correctly answer very simple coding problems. They can explain small code snippets (I’m a hot mess with HTML and appreciate what chatGPT can tell me about it). If you have GitHub Copilot<img src="https://latex.codecogs.com/png.latex?%5E2"> integrated into your coding IDE like RStudio, it’s pretty handy!</p>

<div class="no-row-height column-margin column-container"><div class="">
<p><img src="https://latex.codecogs.com/png.latex?2"> <a href="https://github.com/features/copilot">Copilot</a> A generative AI tool that is <strong>not</strong> <a href="https://copilot.microsoft.com">Microsoft Copilot</a>, a confusing situation since Microsoft owns both products.</p>
</div></div><p>This results in a small improvement in efficiency - maybe 5% (who knows?), but not some quantum leap. Beyond that, I’m pretty disappointed by the outputs from LLMs. These models famously “hallucinate”, producing confident sounding and completely incorrect answers. We are definitely not about to solve all the world’s problems with ChatGPT, or Llama, Gemini, or any of the other chat bots, despite Sam Altman’s <a href="https://www.realclearscience.com/articles/2024/09/30/sam_altman_envisions_an_ai_utopia_its_magical_thinking_1061740.html">excessively optimistic prognoses</a>.</p>
</section>
<section id="why-so-limiting" class="level2" data-number="2">
<h2 data-number="2" class="anchored" data-anchor-id="why-so-limiting"><span class="header-section-number">2</span> Why so limiting?</h2>
<p>LLMs are text prediction models - nothing more, nothing less. They are built by ingesting large quantities of human-generated text-based data and using some rather sophisticated matrix algebra, non-linear transformations and calculus (truly, these models are a mathematical accomplishment). But, at the the end of the day, they produce content based on the most likely string of words for a given query (mathematicians, I know I’m oversimplifying things!! Don’t come at me!!!). They are built on human knowledge, human errors and human biases and hence can amplify all of those joys and sorrows of humanity. And that’s it. That’s all they do. In some ways, an LMM is combination glorified search engine/turbocharged auto-complete, except it needs the power of an entire <a href="https://www.cnbc.com/2024/10/15/big-tech-turns-to-nuclear-energy-to-fuel-power-intensive-ai-ambitions.html">nuclear reactor</a> to do its job.</p>
<p>I know some scientists ask ChatGPT how to statistically analyze experiments. This is not a terrible starting point for statistical analysis, but given hallucinations, I hope those scientists are checking those results. One scientist boasted to me that he could upload data straight into chatGPT and it would analyze it for him. I’m not sure where to start with what is wrong with that process but most certainly, scientists need to know and supervise the statistical model used to analyze their results! This is science 101, my peeps.</p>
<p>As mentioned, LLMs are vastly over-hyped. Sam Altman infamously stated at one point that AI would run ‘experiments’ for us scientists while we slept, enabling leaps and bounds in scientific discovery (I cannot find the original tweet, one that was heavily lambasted by the academic research community but here is <a href="https://www.technologyreview.com/2023/07/05/1075865/eric-schmidt-ai-will-transform-science/">a statement</a> from former Google CEO Eric Schmidt making the same claim). This idea seems dubious to me, mostly because generative AI cannot truly think; its advantage lies in aggregating information.</p>
</section>
<section id="agi-and-llms" class="level2 page-columns page-full" data-number="3">
<h2 data-number="3" class="anchored" data-anchor-id="agi-and-llms"><span class="header-section-number">3</span> AGI and LLMs</h2>
<p>And then there is the claim that these models might gain “AGI” or “artificial general intelligence”. There is not space here to debunk <a href="https://www.nature.com/articles/d41586-024-03911-3">what a specious claim that is</a> (also, see <a href="https://www.newyorker.com/culture/the-weekend-essay/why-ai-isnt-going-to-make-art">this excellent essay</a> explaining why AI does not make art), but the fact that <a href="https://www.theverge.com/2023/5/30/23742005/ai-risk-warning-22-word-statement-google-deepmind-openai">this claim</a> was first raised by AI companies as they monetized their products tells us all we need to know. Sam Altman and company were so deeply concerned about their products gaining AGI and causing human extinction, they decided to commercialize them? Okay, buddy. Nice PR stunt.</p>
<div class="cell">
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://jpiaskowski.gitlab.io/posts/LLMs-utility/index_files/figure-html/unnamed-chunk-1-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="true" aria-label="Toggle callout">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Cash needs of Gen AI
</div>
<div class="callout-btn-toggle d-inline-block border-0 py-1 ps-1 pe-0 float-end"><i class="callout-toggle"></i></div>
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse show">
<div class="callout-body-container callout-body">
<p>This seems a bit obvious to state, but ICYMI: generative AI is a <a href="https://techcrunch.com/2024/10/02/openai-raises-6-6b-and-is-now-valued-at-157b/"><em>very expensive</em> technology</a>, one that is currently without a sustainable business model. That is why these products are being so heavily promoted. AI companies cannot rely on venture capital funding forever; they eventually need customers and cash to survive. Just because AI companies are making wild claims about their technology does not mean anyone should believe it, no matter how many times AI marketing firms repeat those claims or how much advertising money they spend to broadcast those claims to the entire world at maximum volume.</p>
</div>
</div>
</div>
<p>I realize many of us are or were deeply impacted by a movie from our generation showing AI going rogue:</p>
<ul>
<li>2001: A Space Odyssey<br>
</li>
<li>The Terminator<br>
</li>
<li>The Matrix<br>
</li>
<li>M3gan</li>
</ul>
<p>It’s important to remember that these are movies written by screen writers, not pointed warnings from people who understand the perils of specific technologies.<img src="https://latex.codecogs.com/png.latex?%5E3"> While there are genuine messages about being cautious with deadly technologies, we do not have to wholly ascribe to the premise that robots will eventually ‘outsmart’ humans. The more likely scenario is that human will program a machine that may unintentionally or intentionally destroy other humans. This has of course, already been realized. Sad to say, but we temporarily lose control of technology all the time.</p>

<div class="no-row-height column-margin column-container"><div class="">
<p><img src="https://latex.codecogs.com/png.latex?3"> Screenwriters are often concerned with telling a message that is directly relevant to viewers at the time it is written. <em>The Matrix</em> is a story about trans identity and not being forced into gender conformity. <em>The Terminator</em> is concerned with unchecked technological advances along with concerns about nuclear annihilation and the nature of free will versus destiny. Sure, they discuss the perils of technology, but that doesn’t mean they are warnings about sentient robots.</p>
</div></div><p>Overall, I am much less worried about AI becoming sentient and much more concerned about unintended but very real harms caused when AI is deployed by my fellow humans to address real world problems. There are many examples: <a href="https://www.technologyreview.com/2023/10/04/1080801/generative-ai-boosting-disinformation-and-propaganda-freedom-house/">generating misinformation</a>, <a href="https://www.wired.com/story/plainfield-geolitica-crime-predictions/">unreliable ‘predictive policing’</a>, and <a href="https://www.forbes.com/councils/forbestechcouncil/2023/09/25/ai-bias-in-recruitment-ethical-implications-and-transparency/">amplifying bias</a>. And none of these encompasses what is happening as <a href="https://www.yahoo.com/tech/why-internet-filling-nonsense-ai-120000071.html">AI slop overwhelms</a> online and <a href="https://thesummitdev.com/ai-generated-book-grifters-threaten-the-future-of-lace-making/">offline content</a> (i.e.&nbsp;books).</p>
</section>
<section id="the-statisticians-view" class="level2" data-number="4">
<h2 data-number="4" class="anchored" data-anchor-id="the-statisticians-view"><span class="header-section-number">4</span> The Statistician’s View</h2>
<p>A few months ago, I attended the Joint Statistical Meetings (the “JSM” by those of us in the know) put on by the American Statistical Association in Portland, Oregon. The biggest topic of discussion among JSM attendees was AI (largely generative AI) and their underlying architecture, large language models. Are LLMs replacing us as statisticians? Are we all about to become obsolete and should we pivot our careers to production engineer (an actual suggestion I heard at the meetings)?</p>
<p>There was a range of views on the matter: AI researchers in particular seemed to view their craft as the inevitable dominant path for the foreseeable future. A keynote delivered by Jason Matheny of the Rand Corporation rattled off a long list of ways statisticians can and should contribute to the AI landscape. Other attendees remain highly skeptical. One staunch critic, Victor Solo of the University of New South Wales, called LLMs “over hyped” and “pre-scientific”. He gave a talk to a packed, standing room-only audience, objecting to the brute force methodology and over-reliance on empiricism of LLMs over domain knowledge and scientific principles. Many others were more circumspect: LLMs are here whether we like them or not, so how do we adapt? (This is largely my view, but with a healthy dose of skepticism added).</p>
<p>There were innumerable talks about using deep learning (another term for AI), but not specifically generative AI to improve the quality of statistical estimation. I don’t want to spend time chasing down one million references no one reading this blog is likely to follow up on, but this is a rich area of inquiry with many useful applications, especially for predictive modelling. In particular, deep learning has some great potential to assist medical clinicians with diagnosing medical conditions that rely on imaging like cancer detection.</p>
</section>
<section id="ethics-and-lmms" class="level2 page-columns page-full" data-number="5">
<h2 data-number="5" class="anchored" data-anchor-id="ethics-and-lmms"><span class="header-section-number">5</span> Ethics and LMMs</h2>
<p>Naturally, there were a number of ill advised proposed applications for AI presented at the JSM. Probably the most disturbing AI application discussed was using LLMs to replace clinicians for “underserved populations” (the words used by the academicians who led a workshop). These underserved populations may encompass whole regions (e.g.&nbsp;remote rural areas) or groups of people lacking health insurance and access to regular medical care due to their economic circumstances. A large portion of ‘underserved populations’ are poor communities that lack health insurance and may have spotty medical care history, making model based predictions less accurate (these models rely heavily on complete or nearly complete information to provide individualized predictions). AI clinicians for these underserved areas was pitched as “democratizing healthcare” - a surprising term to use given this was the exact language used by Elizabeth Holmes while she perpetuated a <a href="https://en.wikipedia.org/wiki/Bad_Blood:_Secrets_and_Lies_in_a_Silicon_Valley_Startup">years-long fraud</a> for her blood testing company Theranos.This is hardly the association anyone pitching a new technology would want.</p>
<p>As mentioned, this technology could assist actual trained clinicians and hence benefit their patients. But I am skeptical that anyone wants an AI doc bot. People want real services, not a cheap imitation. And is this how things should be? If you’re poor, you get a chat bot providing medical care, and the financially comfortable get real doctors, nurses and actual medical professionals?<img src="https://latex.codecogs.com/png.latex?%5E4"></p>

<div class="no-row-height column-margin column-container"><div class="">
<p><img src="https://latex.codecogs.com/png.latex?4"> Wired magazine recently published <a href="https://www.wired.com/story/wealth-inequality-personal-service-access-artificial-intelligence/">an article</a> on how wealthy inequality affects the personal care economy: “The Rich Can Afford Personal Care. The Rest Will Have to Make Do With AI.”</p>
</div></div><p>While health care LLMs exist, their level of deployment is unclear, and it seems likely that the FDA will intervene on this subject. Nevertheless, the breathless and well meaning enthusiasm for this from AI researchers was disturbing. These researchers appeared to not understand the problem they were proposing to solve nor did they have any investment in the final product. If the technology didn’t work and failed to help their target population, what did it matter to them? Would they even know?</p>
</section>
<section id="energy-usage-and-llms" class="level2 page-columns page-full" data-number="6">
<h2 data-number="6" class="anchored" data-anchor-id="energy-usage-and-llms"><span class="header-section-number">6</span> Energy Usage and LLMs</h2>
<p>This blog post is not intended to be “10 things I hate about gen AI”, but there is one more criticism that should be mentioned: the massive electricity use required for AI model training and deployment. <a href="https://www.bloomberg.com/graphics/2024-ai-data-centers-power-grids/">Bloomberg recently documented</a> how AI data centers are “wrecking havoc” (their words) on the world power grid. If the prospect of AI data centers using vast quantities of electricity feels hypothetical or remote, you may want to look into where your regional power comes from and what sort of AI data centers have or are considering tapping into it your local source. This is a very real threat facing my regional community in North Idaho/Eastern Washington as we try to survive uncertain and increasingly extreme weather. Several large data centers have relocated to the region where I live and <a href="https://www.propublica.org/article/data-centers-clean-energy-washington-state">used so much energy</a>, Washington State is struggling to meet local demand. Meanwhile, the Pacific Northwest has experienced extreme climate events like the <a href="https://en.wikipedia.org/wiki/2021_Western_North_America_heat_wave">2021 heat dome</a> that sent temperatures soaring to 121°F in early summer and a polar vortex in January 2024 that sent temperature plunging to -40°F wind chill. Thousands of people died and regional energy usage spike as we all struggled to stay cool or stay warm during those events. For these extreme climate events, having reliable electricity was a matter of life or death. Is generative AI worth its massive energy debt?<img src="https://latex.codecogs.com/png.latex?%5E5"></p>

<div class="no-row-height column-margin column-container"><div class="">
<p><img src="https://latex.codecogs.com/png.latex?5"> It has been suggested that it is alright to ignore these climate implications because AI will solve the climate crisis for us. Um sure, maybe. That’s technically possible under the framework that most actions have a non-zero probability associated with them, however small. But, there’s currently very thin evidence to support this view.</p>
</div></div></section>
<section id="the-future" class="level2 page-columns page-full" data-number="7">
<h2 data-number="7" class="anchored" data-anchor-id="the-future"><span class="header-section-number">7</span> The Future</h2>
<p>We are <a href="https://www.forbes.com/sites/lanceeliot/2025/01/13/elon-musk-clamors-that-were-running-out-of-data-for-advancing-ai-llms-but-lets-not-overlook-squeezing-out-more-juice-from-data-that-we-already-have/">running out of data</a><img src="https://latex.codecogs.com/png.latex?%5E6"> as the full extent of human-generated text is consumed by LLMs. It has also been shown that training models on LLM-generated text <a href="https://www.nature.com/articles/s41586-024-07566-y">causes them to collapse</a>. However, this is a rapidly advancing field that is likely to overcome these problems, not to mention that LLMs are <a href="https://www.pcmag.com/how-to/how-to-run-your-own-chatgpt-like-llm-for-free-and-in-private">becoming more efficient</a>. Will these changes be enough to make generative AI truly useful and sustainable? Simon Willison (reputable programmer and LLM groker) <a href="https://simonw.substack.com/p/things-we-learned-about-llms-in-2024">reports</a> that currently LLMs can be useful for a wide range of scientific applications, but learning how to use them currently requires a steep learning curve. Easing the barriers to adoption may well be the need advances that develop this year. Let’s all continue to keep on eye on this situation and evaluate it as it unfolds. Nature regularly publishes <a href="https://www.nature.com/collections/cffejhbfjh">excellent articles</a> that explore utility and reliability in the generative AI space. The only thing I ask is that you evaluate these methods with both a welcoming mindset and a healthy skepticism that is grounded in reality.</p>



<div class="no-row-height column-margin column-container"><div class="">
<p><img src="https://latex.codecogs.com/png.latex?%5E6"> Even after <a href="https://www.theguardian.com/technology/2025/jan/10/mark-zuckerberg-meta-books-ai-models-sarah-silverman">pirating many copyrighted works</a>!</p>
</div></div></section>

 ]]></description>
  <guid>https://jpiaskowski.gitlab.io/posts/LLMs-utility/</guid>
  <pubDate>Mon, 13 Jan 2025 17:50:02 GMT</pubDate>
  <media:content url="https://jpiaskowski.gitlab.io/posts/LLMs-utility/featured.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Practicing Hope in 2025</title>
  <link>https://jpiaskowski.gitlab.io/posts/practicing-hope/</link>
  <description><![CDATA[ 




<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://jpiaskowski.gitlab.io/posts/practicing-hope/featured.jpg" class="img-fluid figure-img"></p>
<figcaption>Mural in Portland, Oregon. Artists: Justin Phillip, Kiana Kinchelow, Layna Lewis Ameya Okamoto, A’misa Chiu and Alex Chiu. Photo by Julia Piaskowski.</figcaption>
</figure>
</div>
<p>Several months ago, I listened to a <a href="https://youtu.be/YKMZIzYBgTk?feature=shared">keynote presentation by Allan Downey</a> at the Posit Conference that extolled that “life is getting better”. The point: the world is too negative! The data source: <a href="https://ourworldindata.org/">Our World in Data</a>. The anecdote: we solved the ozone hole! Several more arguments were put forth about how the world is a better place: fewer people dying from natural disasters. Other versions of this talk mention <a href="https://www.vox.com/the-big-idea/2016/12/23/14062168/history-global-conditions-charts-life-span-poverty">declining poverty rate</a> and declining wartime casualties. I have heard a few iterations of this view throughout the years and they all weirdly use the same data source and provide the exact same evidentiary data points about poverty, hunger and the ozone hole.</p>
<p>The main premise of this particular version of that view is that we are all less happy than previous generations because we are exposed to too much negative news on social media. The evidence presented to support this claim was a graph with few data points indicating a change in self reported happiness that is lower for people born in the 1990s and 2000s. Dr.&nbsp;Downey’s suggested solution is that we stop consuming the news. Not just on social media, but all news. When pressed for data and evidence to support his premise by the audience, he said he had “read some books” (no citations provided).<img src="https://latex.codecogs.com/png.latex?%5E1"></p>

<div class="no-row-height column-margin column-container"><div class="">
<p><img src="https://latex.codecogs.com/png.latex?%5E1"> Ironically, prior to committing this sizable ‘correlation-is-causation’ fallacy, Dr.&nbsp;Downey opened his talk by criticizing the entire field of statistics for being irrelevant in the age of high performance computing because they make permutation-based hypothesis testing easier. Even if he is correct that social media is to blame for people’s unhappiness (a pretty big assumption!), there are other proposed explanations from <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC10943642/">FOMO</a>, to <a href="https://bmcwomenshealth.biomedcentral.com/articles/10.1186/s12905-022-01845-4">body image issues</a> to how social media <a href="https://pubmed.ncbi.nlm.nih.gov/31509167/">increases loneliness and withdrawl</a>. Perhaps we do still need statistics to understand causation?</p>
</div></div><p>The most high profile proponent of this idea that life is getting better is Stephen Pinker. In his book <em>The Better Angels of Our Nature</em>, he argues that the world is less violent than historically, but our perceptions are skewed. Stephen Pinker’s premises have been widely challenged and in many cases debunked: <a href="https://www.opendemocracy.net/en/transformation/steven-pinker-s-ideas-are-fatally-flawed-these-eight-graphs-show-why/">here</a>, <a href="https://www.nature.com/articles/d41586-018-02148-1">here</a>, <a href="https://www.vox.com/the-big-idea/2018/5/17/17362548/pinker-enlightenment-now-two-cultures-rationality-war-debate">here</a>, <a href="https://www.vox.com/2015/5/21/8635369/pinker-taleb">here</a>, <a href="https://www.fooledbyrandomness.com/pinker.pdf">here</a>, <a href="https://www.salon.com/2019/01/26/steven-pinkers-fake-enlightenment-his-book-is-full-of-misleading-claims-and-false-assertions/">here</a>, and <a href="https://www.counterfire.org/article/the-darker-angels-of-our-nature-refuting-the-pinker-theory-of-history-and-violence-book-review/">here</a>.</p>
<p>Nevertheless, in some ways, Drs. Downey and Pinker are not wrong. Those of us involved in the criminal justice movement have pointed this out for years: <a href="https://www.pewresearch.org/short-reads/2024/04/24/what-the-data-says-about-crime-in-the-us/">crime is down</a>, yet, the <a href="https://abcnews.go.com/US/us-stats-show-violent-crime-dramatically-falling-rising/story?id=108042096">perception is that crime</a> is out of control. <a href="https://www.npr.org/2024/03/08/1237103158/immigrants-are-less-likely-to-commit-crimes-than-us-born-americans-studies-find">Immigrants commit fewer crimes</a> in the U.S. than citizens and <a href="https://www.forbes.com/sites/jackkelly/2024/03/20/how-immigrants-are-boosting-us-economic-and-job-growth/">spur economic growth</a>, but immigration is presented as a <a href="https://www.foxnews.com/us/illegal-migrants-convictions-murder-rape-child-molestation-captured-us-border">threat to the safety</a> and job security of U.S. citizens and a straight-out ‘<a href="https://www.americamagazine.org/politics-society/2022/09/15/us-mexico-border-immigration-reform-migrants-asylum-crisis-243779">invasion</a>’. <a href="https://www.axios.com/2023/10/17/us-mexico-border-open-borders-myth">No U.S. border is ‘open’</a>, allowing unfettered access to the U.S., although many news sources and politicians have stated the opposite. Yet, we understand why and how these <a href="https://www.scientificamerican.com/article/why-we-believe-the-myth-of-high-crime-rates/">misconceptions are perpetuated</a>: they serve the political interests of people in power or seeking power, who leverage mass media to stoke fear and panic.</p>
<p>However, this premise - that life is getting better and we are pessimists for not seeing that - makes me deeply uncomfortable because it dismisses or flat out ignores the lived experiences of people in this world. Things are very far from equitable across the world, or even among the audience that heard that keynote talk.</p>
<p>One of the speaker’s points is that fewer people die from natural disaster than ever before. But, that really depends on where you live. When Japan experienced the <a href="https://en.wikipedia.org/wiki/2011_T%C5%8Dhoku_earthquake_and_tsunami">Tōhoku earthquake</a>, the 4th largest earthquake ever recorded in history in 2011, just under 20,000 died, mostly due to drowning from the extremely large tsunami that resulted. In 2010, Haiti experienced a smaller yet very damaging <a href="https://en.wikipedia.org/wiki/2010_Haiti_earthquake">earthquake</a>, reaching 7.0 on the Richter scale (Tōhoku was 9.0). While there is no official death toll, estimates of 92,000 to 316,000 were reported. That was followed by a <a href="https://en.wikipedia.org/wiki/2010s_Haiti_cholera_outbreak">cholera outbreak</a> <em>caused</em> by foreign aid workers that killed 4,600 people, and an explosion of waste left by aid workers in a country that lacks robust waste management infrastructure. <a href="https://www.npr.org/2020/01/12/794298546/a-lost-decade-haiti-still-struggles-to-recover-10-years-after-massive-earthquake">Ten years after</a> the earthquake, thousands of Haitians were still displaced, cholera remains a chronic issues, and many of the promised aid and development never materialized. I would never ever say to a Haitian “Hey, look! The average number of deaths from natural disasters have declined over time!” But, we could say that we have better tools to reduce death from natural disasters that we did 20 years ago and impoverished countries like Haiti deserve these as much as rich countries like Japan and the United States. It’s worth considering what needs to change so that poor countries can bear natural disasters with a less catastrophic death toll. The same ideas apply to to other issues: sure, poverty has declined in the U.S., but we are experiencing record homelessness.</p>
<p>Since it is both unhealthy and unhelpful to wallow in despair, we do need another option and thankfully, there is one: practicing hope. We can consciously engaged in and practice the hope that we can all live better lives through our conscious and intentional work towards such a world. By envisioning a more equitable world - specifically thinking of the policies and structures that support communities and working towards implementing those ideas is how we arrive a better world that allows all to thrive. This implicitly asks that we be active members of our community, not passive bystanders.</p>
<p>Practicing hope also means celebrating accomplishments: a policy that lifted thousands or millions of children out of poverty, increases in minimum wage to support families, funding healthcare for the uninsured, and so on. Collectively, we have worked towards and accomplished so many successes that benefit humanity, and we should revel in that.</p>
<p>2025 is going to be hard. We will see attacks on science, a refusal to gather data when it reveals inconvenient truths, and a general lack of humanity towards the most vulnerable people in the United States: children, homeless, the poor and the undocumented. I encourage everyone to consider what you can do to practice hope. Who in your community does not have enough to eat? Who has unstable housing? Who is at risk of being ripped away from their loved ones? What can your community do to help those people? Taking action to support the most vulnerable in my community is where I find my hope.</p>
<blockquote class="blockquote">
<p>Hope doesn’t preclude feeling sadness or frustration or anger or any other emotion that makes total sense. Hope isn’t an emotion, you know? Hope is not optimism. Hope is a discipline…we have to practice it every single day.</p>
<p>— Mariame Kaba, <a href="https://www.haymarketbooks.org/books/1664-we-do-this-til-we-free-us"><em>We Do This ’Til We Free Us</em></a></p>
</blockquote>



 ]]></description>
  <guid>https://jpiaskowski.gitlab.io/posts/practicing-hope/</guid>
  <pubDate>Tue, 02 Jan 2024 17:50:02 GMT</pubDate>
  <media:content url="https://jpiaskowski.gitlab.io/posts/practicing-hope/featured.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Mind the Gap: Mixed Models in R</title>
  <link>https://jpiaskowski.gitlab.io/posts/r-state-of-mlm/</link>
  <description><![CDATA[ 




<p><img src="https://jpiaskowski.gitlab.io/posts/r-state-of-mlm/featured.JPG" class="img-fluid"></p>
<p><em>This is adapted from a <a href="https://youtu.be/bvXc73BK058">talk</a> I gave at <a href="https://www.nimss.org/projects/view/mrp/outline/18798">NCCC-170</a> annual meeting June 16, 2022.</em></p>
<section id="overview-of-the-problem" class="level3" data-number="0.1">
<h3 data-number="0.1" class="anchored" data-anchor-id="overview-of-the-problem"><span class="header-section-number">0.1</span> Overview of the Problem</h3>
<p>The mixed model situation in R is a <a href="https://www.merriam-webster.com/dictionary/hot%20mess">hot mess</a> (that is, it is spectacularly disordered).</p>
<p>The linear mixed model ecosystem in R consists of over <a href="https://bit.ly/3dizzy">80 libraries</a> that either construct and solve mixed model equations or helper packages the process the results from mixed model analysis (this list was derived from a <a href="https://docs.google.com/spreadsheets/d/19itelYaVW0U0gtNtRfqh76ZGt1awlamNcJwT71u_5Uk/edit?usp=sharing">similar list</a> created by <a href="https://github.com/bbolker/mixedmodels-misc/issues/9">Ben Bolker and others</a>). These libraries provide a patchwork of overlapping and unique functionality regarding the fundamental structure of mixed models: allowable distributions, nested and crossed random effects, heterogeneous error structures and other facets. No single library has all possible functionality enabled.</p>
<p>This patchwork of packages makes it very challenging for statisticians to conduct mixed model analysis and to teach others how to run mixed models in R. As a statistical consultant, my job is to help agricultural researchers develop statistical models that match their research aims and implement those models in R or another statistical software. My experience after 4 year of consulting is that many researchers have a hard time time sorting out how to correctly specify their statistical model in R.</p>
<div class="cell">
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://jpiaskowski.gitlab.io/posts/r-state-of-mlm/gap meme.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Please note that none of this is intended as a criticism of current or past package authors. Package authors and maintainers give a tremendous amount of time and effort - often for free - to provide the functionality present in a package. It is not the fault of any individual that the R mixed model ecosystem is so challenging. It is likely more a reflection of how challenging mixed models are to properly specify and implement and the overall flexibility of these models.</p>
<p>But alas, here we are. Let’s explore the specific problems with running mixed models in R.</p>
</section>
<section id="the-issues" class="level3" data-number="0.2">
<h3 data-number="0.2" class="anchored" data-anchor-id="the-issues"><span class="header-section-number">0.2</span> The Issues</h3>
<p><em>(arranged in order how of much grief I think each causes for R users)</em></p>
<section id="problem-dispersed-functionality" class="level4">
<h4 class="anchored" data-anchor-id="problem-dispersed-functionality">Problem: dispersed functionality</h4>
<p>Table of a some example functionality and the packages where it is enabled. This is not a comprehensive list of possible functionality in mixed models or what it implemented in R.</p>
<div class="cell">
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<colgroup>
<col style="width: 52%">
<col style="width: 47%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;">Package</th>
<th style="text-align: left;">Functionality</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">lme4</td>
<td style="text-align: left;">crossed random effects</td>
</tr>
<tr class="even">
<td style="text-align: left;">nlme</td>
<td style="text-align: left;">exp, gaus, lin &amp; pow covariance structures</td>
</tr>
<tr class="odd">
<td style="text-align: left;">spaMM</td>
<td style="text-align: left;">Matérn covariance structure</td>
</tr>
<tr class="even">
<td style="text-align: left;">lme4</td>
<td style="text-align: left;">generalised LMM</td>
</tr>
<tr class="odd">
<td style="text-align: left;">nlme</td>
<td style="text-align: left;">compound symmetry, AR1, ARMA covariance structures</td>
</tr>
<tr class="even">
<td style="text-align: left;">spATS</td>
<td style="text-align: left;">spline-based spatial effects</td>
</tr>
<tr class="odd">
<td style="text-align: left;">lmerGS, lme4qtl, rrBLUP, pedigreemm, asreml, sommer, …</td>
<td style="text-align: left;">kinship relationship matrix (covariance structure)</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>The most popular mixed model package is likely <strong>lme4</strong>, perhaps followed by <strong>nlme</strong> (it’s difficult to quantify this because downloads don’t always reflect usage, and since <strong>nlme</strong> is now part of base R, download stats for that are really wonky).</p>
<p>These packages by themselves can good aims, but the problems arise in complex situations that require combining functionality. While <strong>lme4</strong> is very powerful (and fast!), it lacks essential functionality for including spatial covariates. <strong>nlme</strong> does have that functionality (although not for Matérn, arguable one of the most popular spatial covariance structures), but it is difficult (but not impossible) to specify crossed random effect (they are nested by default in <code>lme()</code> calls). There are several packages that extend <strong>lme4</strong> but to permit inclusion of a kinship based covariance matrix, but combining that with spatial covariates is not possible. And of course, <strong>lme4</strong> <a href="https://stat.ethz.ch/pipermail/r-help/2006-May/094765.html">famously</a> does not compute p-values, a limitation that can be overcome by computing them manually (fun!!!) or using <strong>lmerTest</strong>. But, often users can only use one <strong>lme4</strong> package extender at a time, leaving them to choose which functionality they need most. And while I agree with the spirit of why p-values are not included in the default ANOVA output for <strong>lme4</strong>, this is rarely a persuasive argument for my clients, who want p-values come hell or high water.</p>
</section>
<section id="problem-inconsistent-syntax" class="level4">
<h4 class="anchored" data-anchor-id="problem-inconsistent-syntax">Problem: inconsistent syntax</h4>
<p>Inconsistent syntax is a long standing problem with R and mixed models or any modelling package in R has this problem (and for all those who say “use Tidymodels!” - agreed, and this is addressed later in the post).</p>
<p>Imagine we want to construct a linear mixed model for one fixed effect, <code>x</code>, and one random effect, <code>rep</code>, for a dependent variable, <code>y</code>. These variables are in a data.frame called “mydata” where <code>y</code> and <code>x</code> are numeric, while <code>rep</code> is an unordered factor.</p>
<p>The model:</p>
<p><img src="https://latex.codecogs.com/png.latex?y_%7Bij%7D%20=%20x_i%20+%20rep_j%20+%20%5Cepsilon_%7Bij%7D"></p>
<p>where the error terms, <img src="https://latex.codecogs.com/png.latex?%5Cepsilon_%7Bij%7D"> are distributed as thus:</p>
<p><img src="https://latex.codecogs.com/png.latex?%5Cepsilon_%7Bij%7D%20%5Csim%20N(0,%20%5Csigma_%7Berror%7D)"> and <img src="https://latex.codecogs.com/png.latex?rep_j"> is distributed as:</p>
<p><img src="https://latex.codecogs.com/png.latex?rep_j%20%5Csim%20N(0,%20%5Csigma_%7Brep%7D)"></p>
<p>Below are syntax examples for this model in 4 major mixed modelling packages in R.</p>
<section id="lme4" class="level5">
<h5 class="anchored" data-anchor-id="lme4">lme4</h5>
<p>Perhaps the most widely used package for mixed modelling in R. Considered (by me) to be the successor to <strong>nlme</strong>.</p>
<pre><code>lme4::lmer(y ~ x + (1|rep), data = mydata,  
        na.action = na.exclude, REML = TRUE)</code></pre>
</section>
<section id="nlme" class="level5">
<h5 class="anchored" data-anchor-id="nlme">nlme</h5>
<p>Standard mixed modelling package in R, now part of base R and still widely used (spoiler: I love this package!)</p>
<pre><code>nlme::lme(y ~ x, random = ~ 1|rep, data = mydata, 
       na.action = na.exclude, method = “REML”)</code></pre>
<p>This follow very similar syntax to <strong>lme4</strong>, but the more arguments specified/the more complex things get, the more the syntax diverges (e.g.&nbsp;how weights matrices are specified is rather different between the packages).</p>
</section>
<section id="asreml" class="level5">
<h5 class="anchored" data-anchor-id="asreml">asreml</h5>
<p>A very popular and widely used software in agricultural sciences. It uses a formula interface similar to <strong>nlme</strong> and <strong>lme4</strong>, with slightly different approaches to specifying how to handle missing data and special covariance matrices. The package <strong>sommer</strong> uses a very similar syntax style. Note that <strong>asreml</strong> is not open source and requires an annual license to use.</p>
<pre><code>asreml::asreml(y ~ x, random = ~ rep, data = mydata, 
              na.method.X = 'exclude', 
             na.method.Y = ‘exclude’)</code></pre>
</section>
<section id="rrblup" class="level5">
<h5 class="anchored" data-anchor-id="rrblup">rrBLUP</h5>
<p>A popular package in the plant breeding community. This package does not use a formula object, and instead requires users to specify the independent effects as a design matrix. The other arguments do not follow existing conventions for linear models in R.</p>
<pre><code>rrBLUP::mixed.solve(y = mydata$y, x = {fixed_design_matrix}, 
                    z = {random_design_matrix}, SE = TRUE)</code></pre>
<p>I talk more about Tidymodels below, but if you just can’t wait, tldr: I have not observed many of my clients or other agricultural scientists using Tidymodels for mixed modelling and even if they did, Tidymodels only addresses a very small number of packages.</p>
</section>
</section>
<section id="problem-varied-output" class="level4">
<h4 class="anchored" data-anchor-id="problem-varied-output">Problem: varied output</h4>
<p><em>There are so many special rules to follow.</em></p>
<ol type="1">
<li>Use <strong>lmerTest</strong> to output p-values for <strong>lme4</strong> (but this doesn’t work with <strong>lme4GS</strong> or other add-on packages).<br>
</li>
<li><strong>emmeans</strong> can extract fixed effects, but not BLUPs! (But, <strong>marginaleffects</strong> can calculate BLUPs! 🤩🤩🤩) Instead, check the package for package functions (fingers crossed that BLUP calculation is enabled!) and deal with the wildly varying syntax.<br>
</li>
<li>Not all these packages have methods written to extract output, so you have to hunt through the model object or the summary of the model object. This is annoying (and for many, it can be very mystifying) and results in very brittle code.<br>
</li>
<li>The AR1xAR1 covariance structure (kronecker product of AR1 in two dimensions, each with its own <img src="https://latex.codecogs.com/png.latex?%5Crho">) is implemented in <strong>sommer</strong>, but it does not estimate <img src="https://latex.codecogs.com/png.latex?%5Crho">; <strong>breedR</strong> can do that (but it’s not open source); <strong>INLA</strong> can estimate <img src="https://latex.codecogs.com/png.latex?%5Crho">, but the package uses a Bayesian approach and takes awhile to install and learn.<br>
</li>
<li>…and so much more.</li>
</ol>
<p>Unsurprisingly, people have a hard time navigating this!</p>
<div class="cell">
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://jpiaskowski.gitlab.io/posts/r-state-of-mlm/alice_maze.gif" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>So, users end up implementing sub-optimal solutions (e.g.&nbsp;running <code>aov()</code>, equivalent to <code>PROC ANOVA</code> in SAS, when a mixed model is needed). I can (usually) help them, but is this the right long-term solution? Once these clients leave my office, are they ready to implement different mixed models on their own? And what about the people who never consult with a statistician? Mixed models are a cornerstone of agricultural research (and likely academic research overall), yet the tools available to do this correctly are insufficient.</p>
<div class="cell">
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://jpiaskowski.gitlab.io/posts/r-state-of-mlm/anakin_meme.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="existing-solutions" class="level3" data-number="0.3">
<h3 data-number="0.3" class="anchored" data-anchor-id="existing-solutions"><span class="header-section-number">0.3</span> Existing Solutions</h3>
<p>There have been recent efforts to create a common function call for mixed models with the library <a href="http://multilevelmod.tidymodels.org/"><strong>multilevelmod</strong></a> (part of the Tidymodels family) and a common way to access accessory information with <a href="https://bbolker.github.io/broom.mixed/"><strong>broom.mixed</strong></a>. These umbrella libraries are enormously helpful, but they are incomplete, addressing less than 10 mixed models packages in total.</p>
<section id="multilevelmod-package" class="level4">
<h4 class="anchored" data-anchor-id="multilevelmod-package"><a href="http://multilevelmod.tidymodels.org/">multilevelmod</a> package</h4>
<p>This is part of the <a href="https://www.tidymodels.org/">Tidymodels</a> family, whose goal (among many) is to standardize the syntax for mixed modelling in the R-verse. I am so glad this package exists; it has been sorely needed for <em>years</em> and does simplify the syntax. However, it addresses 4 packages and an extremely limited number of scenarios:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>package</th>
<th>linear</th>
<th>logistic</th>
<th>Poisson</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>lme4</td>
<td>X</td>
<td>X</td>
<td>X</td>
</tr>
<tr class="even">
<td>nlme</td>
<td>X</td>
<td></td>
<td></td>
</tr>
<tr class="odd">
<td>gee</td>
<td>X</td>
<td>X</td>
<td>X</td>
</tr>
<tr class="even">
<td>rstanarm</td>
<td>X</td>
<td>X</td>
<td>X</td>
</tr>
</tbody>
</table>
<p>Again, these package authors are busy, and this task of unifying the mixed model ecosystem is difficult, so no shade intended towards these folks! My point is that implementing a mixed model is still rather challenging from from the user standpoint.</p>
</section>
<section id="broom.mixed-package" class="level4">
<h4 class="anchored" data-anchor-id="broom.mixed-package"><a href="https://bbolker.github.io/broom.mixed/">broom.mixed</a> package</h4>
<p>This is a fantastic package that supports a large number of packages (see below). The highlighted packages are those also supported by <strong>multilevelmod</strong>.</p>
<ul>
<li>brms<br>
</li>
<li>gamlss<br>
</li>
<li>GLMMadaptive<br>
</li>
<li>glmmADMB<br>
</li>
<li><mark>lme4</mark><br>
</li>
<li>mcmc<br>
</li>
<li>MCMCglmm<br>
</li>
<li>mediation<br>
</li>
<li><mark>nlme</mark><br>
</li>
<li>pscl<br>
</li>
<li><mark>rstanarm</mark><br>
</li>
<li>TMB</li>
</ul>
<p><strong>multilevelmod</strong> and <strong>broom.mixed</strong> work like their counterparts in the Tidymodels world. I don’t want to go into the syntax, but you can find examples <a href="https://multilevelmod.tidymodels.org/articles/multilevelmod.html">here</a> and <a href="https://bbolker.github.io/broom.mixed/">here</a>.</p>
</section>
<section id="many-accessory-packages" class="level4">
<h4 class="anchored" data-anchor-id="many-accessory-packages">Many accessory packages:</h4>
<p>There are loads of accessory packages written to ease the burden of extracting output from a mixed model object and/or extending the functionality. These add to the general complexity of specifying a mixed model in R and hence are both a solution and part of the problem.</p>
<p>It’s a big task to name all helper packages for mixed models that I have no interest in doing comprehensively, so here is a short list:</p>
<ul>
<li><a href="https://CRAN.R-project.org/package=afex"><strong>afex</strong></a>: conduct ANOVA</li>
<li><a href="https://CRAN.R-project.org/package=emmeans"><strong>emmeans</strong></a> and <a href="https://CRAN.R-project.org/package=marginaleffects"><strong>marginaleffects</strong></a>: 2 helpful packages for extracted BLUE’s and in in the case of <strong>marginaleffects</strong>, BLUPs.</li>
<li><a href="https://CRAN.R-project.org/package=lmerTest"><strong>lmerTest</strong></a>: get those p-values from <strong>lme4</strong>!</li>
</ul>
<p>There are more (see the google sheets links listed above), but wow, keeping track of this is a major undertaking.</p>
</section>
<section id="tidymodels-style-guide" class="level4">
<h4 class="anchored" data-anchor-id="tidymodels-style-guide"><a href="https://tidymodels.github.io/model-implementation-principles">Tidymodels style guide</a></h4>
<ul>
<li>Naming conventions for arguments<br>
</li>
<li>How information should be returned in ‘predict’ calls, ‘summary’ statements<br>
</li>
<li>what the user-facing function should look like<br>
</li>
<li>usage of S3 method conventions<br>
</li>
<li>how parallel processing occurs<br>
</li>
<li><a href="https://style.tidyverse.org/">Tidyverse style guide</a> (opinionated)</li>
</ul>
<p>Missing from this guide are conventions on the standardized output for (mixed) linear models (log likelihood, residuals, variance components, etc). These things are “missing” because the Tidymodels guide is broadly written for a diverse group of packages/modelling applications in which the standard output from a linear model is not possible or desired. However, in the mixed model landscape, there is common output that users expect; hence it would be useful to codify standards for these types of models.</p>
</section>
</section>
<section id="what-else-is-needed" class="level3" data-number="0.4">
<h3 data-number="0.4" class="anchored" data-anchor-id="what-else-is-needed"><span class="header-section-number">0.4</span> What else Is needed?</h3>
<p>Unfortunately none of these solutions solve one of the most bedeviling problems: running a complex mixed model in R requires using a large patchwork of packages (many of which are not part of Tidymodels) and in some cases, these different functionalities cannot be implemented together.</p>
</section>
<section id="what-else-can-we-do" class="level3" data-number="0.5">
<h3 data-number="0.5" class="anchored" data-anchor-id="what-else-can-we-do"><span class="header-section-number">0.5</span> What else can we do?</h3>
<ul>
<li>Teach Tidymodels to our clients. I admit to not doing this, but I <em>should</em> be doing this.</li>
<li>Encourage teaching of Tidymodels framework at our institutions.</li>
<li>Write an opinionated white paper about recommended functionality and style for any new mixed modelling packages written for R (Who wants more things to do??? And will anyone even read this, let alone follow it?)</li>
<li>Contribute to <a href="https://github.com/tidymodels/multilevelmod"><strong>multilevelmod</strong></a> and <a href="https://github.com/bbolker/broom.mixed"><strong>broom.mixed</strong></a> to expand the packages supported. <em>Important Note: doing this starts with visiting the respective Github repo’s for these packages and finding out what the package authors &amp; maintainers want.</em></li>
</ul>
<p>Questions to ask ourselves:</p>
<ol type="1">
<li>Which is the most important barriers we should address: standardized syntax? standardized output? something else?</li>
<li>What mixed model packages are the most important to the user base?<br>
</li>
<li>Seriously, who is going to do this? Is this grant proposal worthy?<br>
</li>
<li>What about the functionality patchwork problem? What on this green earth should we do about that?</li>
</ol>
<p>Other ideas? (I want to hear them! DM me on Twitter: <span class="citation" data-cites="SeedsAndBreeds">@SeedsAndBreeds</span>)</p>
</section>
<section id="final-thoughts" class="level3" data-number="0.6">
<h3 data-number="0.6" class="anchored" data-anchor-id="final-thoughts"><span class="header-section-number">0.6</span> Final Thoughts</h3>
<p>I decided to write this after years of trying to make mixed models work for my clients and often seeing them frustrated. Perhaps our applications seem niche - but, there are thousands of agricultural researchers in the world. And questions about how to build a linear mixed model and conduct ANOVA are by far the most common FAQ I encounter. Common scenarios in this subject include:</p>
<ol type="1">
<li>A multilevel field trial (imagine 3-5 treatments, each with 2-10 levels, perhaps one a time series, because ag scientists love those complex experiments!). In many cases, we need to account for spatial variation.</li>
<li>A field trial with one fixed effect and one random effect, but two different heterogeneous covariance matrices need to be included: one for spatial variation and another for relatedness among the treatments.</li>
<li>All of the previous experiments plus special designs: split plot, split-split plot, Latin square, incomplete block, augmented design….</li>
<li>All the previous experiments, but now we have a beta-distributed variable! Or a negative binomial (the experimental variables I see rarely meet the expectations of a Poisson distribution).</li>
<li>A mixed model with tons of zeros! And maybe a time series component, as well.</li>
</ol>
<p>There are ways to solve these problems–<em>easily</em>–in other (paid) software such as SAS or asreml-R. But for whatever reasons that I am not in control of, people want to use R and the non-proprietary libraries that accompany it. And often they end up implementing sub-optimal solutions based on a lack of understanding of how to properly specify a mixed model in R.</p>
<p>Should we abandon users to the confusing and incomplete maze of mixed models in open-source R or should we help them and ultimately create a more sustainable mixed model ecosystem?</p>
<blockquote class="twitter-tweet blockquote">
<p lang="en" dir="ltr">
the R mixed model ecosystem <a href="https://t.co/wx5nLM1soc">https://t.co/wx5nLM1soc</a>
</p>
— ag stats stan (<span class="citation" data-cites="SeedsAndBreeds">@SeedsAndBreeds</span>) <a href="https://twitter.com/SeedsAndBreeds/status/1543653142692184065?ref_src=twsrc%5Etfw">July 3, 2022</a>
</blockquote>
<script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<p>A video of this talk can be viewed on <a href="https://youtu.be/bvXc73BK058">youtube</a>.</p>


</section>

 ]]></description>
  <category>R</category>
  <category>statistical consulting</category>
  <category>mixed linear models</category>
  <guid>https://jpiaskowski.gitlab.io/posts/r-state-of-mlm/</guid>
  <pubDate>Tue, 05 Jul 2022 17:50:02 GMT</pubDate>
  <media:content url="https://jpiaskowski.gitlab.io/posts/r-state-of-mlm/featured.JPG" medium="image"/>
</item>
<item>
  <title>Bad Data Management: A Star Wars Story</title>
  <link>https://jpiaskowski.gitlab.io/posts/starwars-bad-data-management/</link>
  <description><![CDATA[ 




<p><img src="https://jpiaskowski.gitlab.io/posts/starwars-bad-data-management/featured.jpg" class="img-fluid"></p>
<p>Most of us think of Star Wars as the rebellion versus the empire – good versus evil with key figures: the Jedi, the Sith, Darth Vader, Luke Skywalker, the Emperor, Rey, Kylo Ren. But, The downfall of the governing bodies was not Darth Vader, Luke Skywalker, Kylo Ren or Palpatine. Actually, Star Wars is a story of really bad data management practices.</p>
<section id="the-republic" class="level4">
<h4 class="anchored" data-anchor-id="the-republic">The Republic:</h4>
<p>The Jedi maintained decent, well-organised archives in a large library and they even had paid librarians on staff. But any Jedi can delete information and no record is left regarding this? For heaven’s sake, an entire planet was removed from said archives That ain’t good. It led to the Clone wars and eventual rise of the Galactic Empire. It also turns out that a person just has to look like a Jedi in order <a href="https://starwars.fandom.com/wiki/Holocron_Heist">to steal secured jedi archives</a>.</p>
<p><img src="https://jpiaskowski.gitlab.io/posts/starwars-bad-data-management/younglings.png" class="img-fluid"></p>
</section>
<section id="original-galatic-empire" class="level4">
<h4 class="anchored" data-anchor-id="original-galatic-empire">Original Galatic Empire:*</h4>
<p>This is where all the bad stuff starts. Initially, they had a good system for managing their vasts amount of data and an off-site backup with a very powerful firewall. However, once that firewall was breached, there was poor security inside - I mean, a dead archivist’s hand could be used to access <em>the entire system</em>, presumably as a root user. Their storage facility also relied on a rather inconvenient system for accessing data: a massive tower than required a remote-controlled tool for physical retrieval of data files.</p>
<p><img src="https://jpiaskowski.gitlab.io/posts/starwars-bad-data-management/archive_joystick.png" class="img-fluid"></p>
<p>The tool itself required manual operation and apparently the entire facility had no backup generator to maintain security and functioning in case of a power loss. Incredibly, there was also no search tool. Data archives had to be <em>browsed</em> (what???). it’s really quite astonishing that anyone ever found what they needed. Options for sending out the data were also remarkably cumbersome - a satellite dish the size of a Star Destroyer has to manually turned in the correct direction to send a file out (was the Empire capable of automating anything?). I also wonder about the file compression capabilities - seriously, is there any file so large it needs a satellite dish of that size?</p>
<p><img src="https://jpiaskowski.gitlab.io/posts/starwars-bad-data-management/scarif_tower.JPG" class="img-fluid"></p>
</section>
<section id="the-first-order" class="level4">
<h4 class="anchored" data-anchor-id="the-first-order">The First Order:</h4>
<p>The First Order inherits a number of problems from the original Galactic Empire, most notably insufficient backups resulting in lost information. A map to Luke Skywalker is lost, making it nigh impossible to find him. A map to Exogol had two copies ever made, one of them on a destroyed death star sitting in the middle of raging ocean? It’s amazing these were very found. Without these maps, we have no Sith and no Jedi (maybe not such a bad thing).</p>
<p><img src="https://jpiaskowski.gitlab.io/posts/starwars-bad-data-management/skywalker_map.jpg" class="img-fluid"></p>
<p>The point is that if the Jedi had better data practices, then they might have avoided the rise of the empire. And perhaps if the Empire had better data practices, they may not undergone such a rapid downfall.</p>
<p><img src="https://jpiaskowski.gitlab.io/posts/starwars-bad-data-management/death_star_wreckage.jpg" class="img-fluid"></p>
</section>
<section id="what-happens-with-good-data-management" class="level4">
<h4 class="anchored" data-anchor-id="what-happens-with-good-data-management">What happens with good data management:</h4>
<ul>
<li>Secure data that can only be modified by authorised users</li>
<li>Validation of data values to prevent errors</li>
<li>Data is accessible: it can be accessed in many places, by many, in formats that are easy to use</li>
<li>Stored data is easy to search and summarise</li>
<li>There are sufficient backups if something goes wrong</li>
</ul>
</section>
<section id="wait-this-actually-matters" class="level4">
<h4 class="anchored" data-anchor-id="wait-this-actually-matters">Wait! This actually matters!</h4>
<p>This is more than a story to amuse folks, though. Poor data management is a rampant issue across academia. I have observed that most researchers do not document their data processing in sufficient detail to recreate the process. Who else has read this statement “outliers were removed” with no details into how those outliers were eliminated or the numerical values of those “outliers”?</p>
<p>From a research standpoint this means the analytical procedure is not replicable. That means someone starting with the same raw data will not obtain the same results following the described analytical procedure – because the description was inadequate. This can also mean data are unreliable. If the original version of data become lost as individuals clean up the data and do not document their process, then there is no way to evaluate if the cleaning was correctly done or justified. Data loss is always a risk when files are emailed around rather than shared via a more permanent data storage solution. All of these risks become amplified when an individual leaves a research program and can no longer be reached to resolve data questions.</p>
</section>
<section id="tools-for-better-data-management" class="level4">
<h4 class="anchored" data-anchor-id="tools-for-better-data-management">Tools for better data management</h4>
<p>Handily, many many tools exist to assist in data management. I give a bare bones outline in this <a href="../../post/workflow_basics/">post</a> (please read this!!). Software Carpentry provides an excellent outline of essential processes in their document <a href="https://swcarpentry.github.io/good-enough-practices-in-scientific-computing/">Good Enough Practices for Scientific Computing</a>.</p>
<p>Below is an even more bare ‘bare bones’ outline.</p>
<p>One of the best solutions is to put your data in a database. This a great tool for large quantities of data that follow a regular format and are frequently updated - such as variety testing data.</p>
<p>However, most agricultural researchers are not so lucky to have such structured data. At the very least, maintaining research outputs in a shared and secured location is a good start. Archiving raw versions of data is paramount. This maybe never be needed, but if it is needed, there is no replacement if those data are lost. Requiring complete documentation from all research contributors on data set generation and processing is also good. A “codebook” is another great tool. This is a file accompanying a data set that provides the name of each column, what data are present in that column, and optionally, the units of those data and the range of values expected. If a column contains contains numeric values between 0 and 100, then others will know that 980 is probably an error.</p>
<p>Most of the researchers I work with were trained in a different era - when data was expensive to obtain and as a result, there was considerably less data to deal with. I count myself among this group. At that time, data management tools were less relevant because we had the time to comprehensively examine a data set for errors. Furthermore, data sharing and data reuse were not widely done. But, we all now those days are long over. We are now expected to process a large quantity of data rapidly, analyse it and eventually archive it publicly for possible reuse by someone else. Engaging in practices that enable quality data management is essential for participation in today’s research environment.</p>


</section>

 ]]></description>
  <category>data workflow</category>
  <category>research reproducibility</category>
  <guid>https://jpiaskowski.gitlab.io/posts/starwars-bad-data-management/</guid>
  <pubDate>Sat, 01 Feb 2020 17:50:02 GMT</pubDate>
  <media:content url="https://jpiaskowski.gitlab.io/posts/starwars-bad-data-management/featured.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Faster R Scripts through Code Profiling</title>
  <link>https://jpiaskowski.gitlab.io/posts/speed-up-r-code/</link>
  <description><![CDATA[ 




<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://jpiaskowski.gitlab.io/posts/speed-up-r-code/featured.jpg" class="img-fluid figure-img"></p>
<figcaption><em>Image credit: <a href="https://www.hackerearth.com/blog/python/faster-python-code/">HackerImage website</a></em></figcaption>
</figure>
</div>
<section id="sources" class="level5">
<h5 class="anchored" data-anchor-id="sources">Sources</h5>
<p>Thomas Lumley, Github repo <a href="https://github.com/tslumley/useRfasteR">useRfasteR</a><br>
Hadley Wickham, <a href="http://adv-r.had.co.nz/Profiling.html">Profiling</a>, <em>Advanced R</em><br>
Dirk Eddelbuettel, <a href="http://www.rcpp.org/">Rcpp</a></p>
</section>
<section id="the-process-for-improving-code" class="level4">
<h4 class="anchored" data-anchor-id="the-process-for-improving-code">The Process for Improving Code:</h4>
<p>(quote from <em>Advanced R</em>)</p>
<blockquote class="blockquote">
<ol type="1">
<li>Find the biggest bottleneck (the slowest part of your code).</li>
<li>Try to eliminate it (you may not succeed but that’s ok).</li>
<li>Repeat until your code is “fast enough.”</li>
</ol>
</blockquote>
<p><strong>Easy peasy, right???</strong></p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://jpiaskowski.gitlab.io/posts/speed-up-r-code/owl.png" class="img-fluid figure-img"></p>
<figcaption>owl</figcaption>
</figure>
</div>
</section>
<section id="some-general-guidelines-for-speeding-up-r-code" class="level4">
<h4 class="anchored" data-anchor-id="some-general-guidelines-for-speeding-up-r-code">Some general guidelines for speeding up R code</h4>
<ol type="1">
<li>Use data frames less - they are expensive to create, often copied in whole when modified, and their rownames attribute can really slow things down.</li>
<li>Be wary of using functions that copy objects in whole: c(), append(), cbind(), rbind(), or paste(). When used in loops, you can get a massive proliferation of objects in memory.</li>
<li>Use vectorised functions:
<ul>
<li>apply, lapply, sapply, vapply, tapply, mapply</li>
<li>rowSums, colSums, rowMeans, colMeans, cumsum, diff</li>
</ul></li>
<li>Base functions are designed to handle wildly different input. Consider rewriting base functions for highly repetitive tasks.</li>
<li>Use parallel::mclapply for parallelising functions.</li>
<li>Consider an optimized matrix algebra library (beyond BLAS) for better performance (e.g.&nbsp;<a href="https://developer.apple.com/documentation/accelerate/blas">Apple vecLib BLAS</a>, <a href="https://www.openblas.net/">openBLAS</a>).</li>
<li>If you work with sparse matrices, use tools for them like the package ‘Matrix’.<br>
</li>
<li>For huge objects, consider storing the information in a database and accessing it with ‘dbplyr’. The packages ‘dbglm’ and ‘tidypredict’ will also do model fitting with data inside a database.</li>
<li>Another solution for large objects are specialized formats like <a href="https://portal.hdfgroup.org/display/support">HDF5</a> or <a href="https://www.unidata.ucar.edu/software/netcdf/">netCDF</a>.</li>
<li>Take advantage of the Rcpp suite of programs - not just for C/C++ programmers (e.g.&nbsp;RcppArmadillo::fastlm).</li>
<li>Use an alternative implementation of R (e.g., <a href="https://github.com/oracle/fastr%5D">fastR</a>, <a href="http://www.pqr-project.org/">pqR</a>).</li>
<li>Check your code with benchmarking!!!</li>
</ol>
</section>
<section id="lets-do-some-benchmarking" class="level4">
<h4 class="anchored" data-anchor-id="lets-do-some-benchmarking">Let’s do some benchmarking!</h4>
<p>Important: don’t (re)install ‘compiler’; you should just be able to load it in R v3.5 and later.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1">pck <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pryr"</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"microbenchmark"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"profvis"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"compiler"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mnormt"</span>)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">invisible</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(pck, library, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">character.only =</span> T))</span></code></pre></div>
</div>
<p>First, Turn off the just-in-time compiler. Note that return value is what the JIT was set at previously (default = 3).</p>
<pre><code>enableJIT(0)</code></pre>
<section id="the-microbenchmark-function" class="level5">
<h5 class="anchored" data-anchor-id="the-microbenchmark-function">The microbenchmark function</h5>
<ul>
<li>for evaluating small snippets of code</li>
<li>below is a comparison of several approaches to calculating a mean</li>
</ul>
<div class="cell">
<div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb3-2">  m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb3-3">  data.x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(m, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e4</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> x))</span>
<span id="cb3-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cbind"</span>, data.x)</span>
<span id="cb3-5">}</span>
<span id="cb3-6"></span>
<span id="cb3-7">some_data <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">a</span>()</span>
<span id="cb3-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(some_data)</span>
<span id="cb3-9"></span>
<span id="cb3-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">microbenchmark</span>(</span>
<span id="cb3-11">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean_loop =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(some_data, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, mean),</span>
<span id="cb3-12">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean_vec =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colMeans</span>(some_data),</span>
<span id="cb3-13">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean_manual =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(some_data, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(x)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(x)),</span>
<span id="cb3-14">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean_manual_ultra =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(some_data, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x){</span>
<span id="cb3-15">    total <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb3-16">    n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb3-17">    i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb3-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(x[i])) {</span>
<span id="cb3-19">      total <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> total <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> x[i]</span>
<span id="cb3-20">      n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb3-21">      i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb3-22">    }</span>
<span id="cb3-23">    total<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>n</span>
<span id="cb3-24">  })</span>
<span id="cb3-25">)</span></code></pre></div>
</div>
</section>
<section id="prevent-multiple-dispatch" class="level5">
<h5 class="anchored" data-anchor-id="prevent-multiple-dispatch">Prevent multiple dispatch:</h5>
<ul>
<li>the function mean() is meant to handle several different types of data</li>
<li>specifying the method (thus implying a certain type of input) can speed up the process for small data sets</li>
<li>the function mean() calls a different function depending on the object specified:</li>
</ul>
<div class="cell">
<div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">methods</span>(mean)</span>
<span id="cb4-2"></span>
<span id="cb4-3">x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">e2 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">e4 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e4</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">e6 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span>))</span>
<span id="cb4-4"></span>
<span id="cb4-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(x1, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x)</span>
<span id="cb4-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">microbenchmark</span>(</span>
<span id="cb4-7">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(x),</span>
<span id="cb4-8">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean.default</span>(x)</span>
<span id="cb4-9">  )</span>
<span id="cb4-10">)</span></code></pre></div>
</div>
<p>I suspect the improvement in speed for smaller objects but larger objects is related to big O notation – these smaller objects are impacted by constants</p>
<p>Other approaches for finding source code:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># tracking package type, etc</span></span>
<span id="cb5-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">otype</span>(mean)</span>
<span id="cb5-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ftype</span>(mean)</span>
<span id="cb5-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">showMethods</span>(mean) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#for S4</span></span>
<span id="cb5-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">methods</span>(mean)</span></code></pre></div>
</div>
<p>The function methods() does not always work, but there are alternatives:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">methods</span>(var)</span>
<span id="cb6-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getAnywhere</span>(var)</span></code></pre></div>
</div>
</section>
<section id="find-the-bottlenecks-with-rprof" class="level5">
<h5 class="anchored" data-anchor-id="find-the-bottlenecks-with-rprof">Find the bottlenecks with Rprof()</h5>
<ul>
<li>writes stack calls to disk along with memory usage and vector duplication</li>
<li>you create a .prof file to do this and then close it when done with profiling</li>
</ul>
<div class="cell">
<div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">Rprof</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"permute.prof"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">memory.profiling =</span> T)</span>
<span id="cb7-2"></span>
<span id="cb7-3">sigma.mv <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb7-4">sigma.mv[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">upper.tri</span>(sigma.mv)] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span></span>
<span id="cb7-5">sigma.mv[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lower.tri</span>(sigma.mv)] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span></span>
<span id="cb7-6"></span>
<span id="cb7-7">mvn.data <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rmnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">varcov =</span> sigma.mv)</span>
<span id="cb7-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colnames</span>(mvn.data) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))</span>
<span id="cb7-9"></span>
<span id="cb7-10">kmeans.Ftest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(kmean_obj) {</span>
<span id="cb7-11">  df<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(kmean_obj<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb7-12">  df<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.2</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(kmean_obj<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cluster) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(kmean_obj<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size)</span>
<span id="cb7-13">  betw_ms <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> kmean_obj<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>tot.withinss<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>df<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1</span></span>
<span id="cb7-14">  with_ms <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> kmean_obj<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>betweenss<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>df<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.2</span></span>
<span id="cb7-15">  fratio <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> betw_ms<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>with_ms</span>
<span id="cb7-16">  pval <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pf</span>(fratio, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">df1 =</span> df<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">df2 =</span> df<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> F)</span>
<span id="cb7-17">  stuff <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(fratio, df<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.1</span>, df<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">.2</span>, pval)</span>
<span id="cb7-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(stuff) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'F-ratio'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'df 1'</span>,<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'df 2'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'p-value'</span>)</span>
<span id="cb7-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">return</span>(stuff)</span>
<span id="cb7-20">}</span>
<span id="cb7-21"></span>
<span id="cb7-22">kmeans.optimiz <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) {</span>
<span id="cb7-23">    results <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kmeans</span>(mvn.data, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">centers =</span> x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nstart =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">algorithm =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"MacQueen"</span>,</span>
<span id="cb7-24">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">iter.max =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>)</span>
<span id="cb7-25">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kmeans.Ftest</span>(results)</span>
<span id="cb7-26">})</span>
<span id="cb7-27"></span>
<span id="cb7-28">kmeans.final <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rbind"</span>, kmeans.optimiz)</span>
<span id="cb7-29"></span>
<span id="cb7-30"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">Rprof</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>)</span>
<span id="cb7-31"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summaryRprof</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"permute.prof"</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#, memory = "both")</span></span></code></pre></div>
</div>
</section>
<section id="use-profvis-to-visualize-performance" class="level5">
<h5 class="anchored" data-anchor-id="use-profvis-to-visualize-performance">Use profvis to visualize performance</h5>
<ul>
<li>nice graphical output<br>
</li>
<li>native in RStudio (there is extensive <a href="https://support.rstudio.com/hc/en-us/articles/218221837-Profiling-with-RStudio">documentation</a>)<br>
</li>
<li>you can view output in browser</li>
</ul>
<div class="cell">
<div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">p <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">profvis</span>({</span>
<span id="cb8-2">mean_loop <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(some_data, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, mean)</span>
<span id="cb8-3">mean_vec <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colMeans</span>(some_data)</span>
<span id="cb8-4">mean_manual <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(some_data, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(x)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(x))</span>
<span id="cb8-5">mean_manual_ultra <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(some_data, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x){</span>
<span id="cb8-6">  total <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb8-7">  n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb8-8">  i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb8-9">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(x[i])) {</span>
<span id="cb8-10">      total <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> total <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> x[i]</span>
<span id="cb8-11">      n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb8-12">      i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb8-13">    }</span>
<span id="cb8-14">    total<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>n</span>
<span id="cb8-15">  })</span>
<span id="cb8-16">})</span>
<span id="cb8-17">htmlwidgets<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">saveWidget</span>(p, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"profile.html"</span>)</span>
<span id="cb8-18"></span>
<span id="cb8-19"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">browseURL</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"profile.html"</span>)</span></code></pre></div>
</div>
</section>
<section id="explore-source-code" class="level5">
<h5 class="anchored" data-anchor-id="explore-source-code">Explore source code</h5>
<p><strong>How to access function source code</strong> (if you didn’t write the function yourself)</p>
<ol type="1">
<li>Type the function name (without parentheses): <code>eigen</code></li>
<li>Find namespace and methods associated: <code>methods("princomp"); getAnywhere("princomp.default")</code></li>
<li>Use pryr::show_c_source() to search for C code on GitHub (which may or may not be helpful)</li>
<li>Download the entire package and explore the code</li>
</ol>
<div class="cell">
<div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">svd</span>
<span id="cb9-2">La.svd</span>
<span id="cb9-3"></span>
<span id="cb9-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">try</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">show_c_source</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">.Internal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">La_svd</span>(x))))</span>
<span id="cb9-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">show_c_source</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">.Internal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(x)))</span>
<span id="cb9-6"></span>
<span id="cb9-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">download.packages</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"broman"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">repos =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://cloud.r-project.org"</span>,</span>
<span id="cb9-8">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">destdir =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getwd</span>(),<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">type =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"source"</span>)</span></code></pre></div>
</div>
</section>
<section id="trace-objects-copied" class="level5">
<h5 class="anchored" data-anchor-id="trace-objects-copied">Trace objects copied</h5>
<ul>
<li>use tracemem() to track particular objects</li>
</ul>
<div class="cell">
<div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> letters[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)]</span>
<span id="cb10-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tracemem</span>(a)</span>
<span id="cb10-3">a[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Z"</span></span>
<span id="cb10-4">b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> a[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># not copied</span></span></code></pre></div>
</div>
</section>
<section id="memory" class="level5">
<h5 class="anchored" data-anchor-id="memory">Memory</h5>
<ul>
<li>How much memory is being used? Note that R requests memory from your computer in big chunks then manages it itself.</li>
</ul>
<div class="cell">
<div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mem_used</span>()</span>
<span id="cb11-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">object.size</span>(x1) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#base</span></span>
<span id="cb11-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">object_size</span>(x1) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#pryr</span></span>
<span id="cb11-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">compare_size</span>(x1) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#between base R and pryr</span></span></code></pre></div>
</div>
<p>Read the <a href="https://www.rdocumentation.org/packages/pryr/versions/0.1.4">documentation for pryr functions</a> for more useful functions.</p>
<p>Now that we are all done, turn the JIT compiler back on:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">enableJIT</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div>
</div>
</section>
<section id="more-tips-from-advanced-r" class="level5">
<h5 class="anchored" data-anchor-id="more-tips-from-advanced-r">More Tips from <em>Advanced R</em></h5>
<p>These are designed to reduce internal checks</p>
<ol type="1">
<li>read.csv(): specify known column types with colClasses.<br>
</li>
<li>factor(): specify known levels with levels.<br>
</li>
<li>cut(): don’t generate labels with labels = FALSE if you don’t need them, or, even better, use findInterval().<br>
</li>
<li>unlist(x, use.names = FALSE) is much faster than unlist(x).<br>
</li>
<li>interaction(): if you only need combinations that exist in the data, use drop = TRUE.</li>
</ol>
</section>
</section>
<section id="remember" class="level3" data-number="0.1">
<h3 data-number="0.1" class="anchored" data-anchor-id="remember"><span class="header-section-number">0.1</span> Remember!</h3>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://jpiaskowski.gitlab.io/posts/speed-up-r-code/xkcd1205.png" class="img-fluid figure-img"></p>
<figcaption>xkcd1205</figcaption>
</figure>
</div>
<p><a href="https://xkcd.com/1205/">xckd comic</a></p>


</section>

 ]]></description>
  <category>R</category>
  <category>code profiling</category>
  <guid>https://jpiaskowski.gitlab.io/posts/speed-up-r-code/</guid>
  <pubDate>Wed, 19 Sep 2018 17:50:02 GMT</pubDate>
  <media:content url="https://jpiaskowski.gitlab.io/posts/speed-up-r-code/featured.jpg" medium="image" type="image/jpeg"/>
</item>
<item>
  <title>Best Practices for Data Workflows in Ag Science</title>
  <link>https://jpiaskowski.gitlab.io/posts/worflow-basics/</link>
  <description><![CDATA[ 




<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://jpiaskowski.gitlab.io/posts/worflow-basics/featured.jpg" class="img-fluid figure-img"></p>
<figcaption><em>Image credit: <a href="https://www.zef.de/index.php?id=1261"><strong>Glowa Volta</strong></a></em></figcaption>
</figure>
</div>
<p>I was struggling with the data set. The first 50 rows were summary stats (…I think), and then the actual data started. The file was over 250 columns wide, composed largely of phenotypic traits. Perhaps one third of the columns were unique variables gathered over several years, but, the variable names were inconsistent across years. Actually, there was no information on the variables, what they were measuring, and what scale they were on. The closest hint was a pattern of color coding applied to groups of columns: yellow, green, blue. There appeared to be partial duplication and/or combination of of some columns, but we could not reconstruct exactly what had happened to the data. No one could recall the full history of the file, what that color coding meant, who had pre-processed data, or what they had done. We did know that the raw data were long lost.</p>
<p>This was the not the first nor the last messy data set with an unknown history that complicated my capacity to organize and analyse the information.</p>
<p>Other problems I encountered with poorly managed data sets:</p>
<ul>
<li>Date sets with outliers removed based on individual’s researchers assessment on what looked weird or not.</li>
<li>An Excel file several thousand lines with miscellaneous comments added every so often indicating a data point may be suspect.</li>
<li>An Excel file several sheets wide of the same information across different years - yet the column names did not match, and some sheets included summary stats for groups of data, using empty rows to differentiate groups (again, I think this was what going on…).</li>
</ul>
<p>There’s no way to sugarcoat it: management of raw experimental data and the analysis workflow is largely abysmal in the agricultural sciences, my academic home for 14 years. The process of cleaning, rearranging, filtering and preparing experimental data for downstream analyses is poorly described, if at all, in most papers. As many of know, much of data conditioning and preparation is done by students and technicians with little formal guidance or documentation of their work.</p>
<p>Since data sets can and should live on for decades - as part of long-term agriculture research, for meta-analyses or other uses, understanding how the raw data were parsed, cleaned and interpreted is important. Assumptions that made sense in the initial analysis may need re-evaluation later. Intermediate files can turn out to be useful. Organization of an analysis workflow can help researchers conduct their research in a regimented and reproducible way.</p>
<p>Here are a few concrete recommendations for improving workflow:</p>
<ul>
<li>Archive the raw, unaltered version of data set.</li>
<li>Create a consistent directory structure for each project - that way you are storing things consistently and can find them. Really, this makes things easier for everyone.</li>
<li>For a data set, each column should be include only type of data corresponding to the column name. These data can be on different scales. For example, if one column indicates the type of variable (e.g.&nbsp;pH, moisture content, nitrate concentration), another columns could indicate the actual value for that trait and observation. It is less confusing if a column only contain a similar type of data (e.g <em>raw</em> OR <em>transformed</em> OR <em>mean value</em>), not data and summary stats together.</li>
<li>Avoid use of formatting that cannot be interpreted as plain text. By this, I mean do not insert comments in Microsoft office files, or use text formatting tools (bolding, color coding) to differentiate observations. This information can easily become lost to time and does not translate well to other software, especially command-line software. Comments, categorical variables, et cetera should each have their own column.</li>
<li>Summary stats of a data set belong in their own table or file.</li>
<li>Use a non-proprietary format like CSV or TXT.</li>
<li>Avoid creating data that relies on a particular order of the observations (for instance, every 5th row is the mean of the previous 4 rows). One sorting step can ruin this. If a special order is needed, create a column which implements this.</li>
<li>Make a “codebook” documenting what each variable means, what scale it is on, expected levels or range of data. This can be one sheet of information - very brief, but handy. Giving variables short, descriptive names is also helpful.</li>
<li>Document what happens to a data set - and make that information available to others. I prefer to use a command line tool like R, but a text file could do. This is to ensure your work can be duplicated. I realize programming is not for everyone, but using a command-line program like R, Python, Julia, SAS, or even bash, is one of the best ways to document how information is pre-processed. Changes made through point-and-click interfaces like Excel are not reproducible because they are almost always incompletely documented or not documented at all. In addition, manual manipulation in a spreadsheet program also results in user-generated errors: misspellings, misclassifications, cut-and-paste errors and so on.</li>
<li>Accountability and follow up: attach people’s names to their data and/or analysis.</li>
<li>Back up your data: across at least 2 locations over the life of your project. Version control make it possible for your work to be undone by accessing earlier versions. Git is one such tool, but saving intermediate file versions (often!) can also help. By providing descriptive comments at each new commit (a version), that can help downstream researchers sift through previous versions of the data. Also, some cloud storage providers (like Dropbox) offer options for data recovery.</li>
<li>Coordinate with project collaborators regarding workflow expectations and processes</li>
</ul>
<p>The core reason I am interested in these issues is to improve reproducibility. As I dealt with the aforementioned issues with data, I could not help but wonder if I was making the right choices with the data, and wish that I had more information on the background of these legacy data sets. This is particularly important as meta-studies continue to gain in popularity. Unifying data sets and leveraging their combined power is one of the priorities for agricultural productivity identified by the National Academy of Sciences in their recent report, <a href="https://www.nap.edu/resource/25059/ScienceBreakthroughs2030ReportBrief.pdf"><em>Science Breakthroughs to Advance Food and Agricultural Research by 2030</em></a>.</p>
<p>For more information, see this <a href="https://www.tandfonline.com/doi/full/10.1080/00031305.2017.1375989"><em>excellent article</em></a> by Kara Woo and Karl Broman - it’s short and gives easy-to-follow best practices when working with spreadsheets.</p>
<p>Scott Long at the University of Indiana put together an <a href="https://www.ihrp.uic.edu/files/Workflow%20Slides%20JSLong%20110410.pdf">informative set of slides</a> delving further into the principles of data workflow. Patrick Schloss, of the bioinformatics program <em>mothur</em>, recently published an <a href="https://mbio.asm.org/content/9/3/e00525-18">article</a> delving into the problem of reproducibility in microbiome work and how to fix it. Among many things, he recommended implementing robust workflow practices.</p>



 ]]></description>
  <category>R</category>
  <category>data workflow</category>
  <category>research reproducibility</category>
  <guid>https://jpiaskowski.gitlab.io/posts/worflow-basics/</guid>
  <pubDate>Tue, 07 Aug 2018 17:50:02 GMT</pubDate>
  <media:content url="https://jpiaskowski.gitlab.io/posts/worflow-basics/featured.jpg" medium="image" type="image/jpeg"/>
</item>
</channel>
</rss>
