<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tania Osadcha on Medium]]></title>
        <description><![CDATA[Stories by Tania Osadcha on Medium]]></description>
        <link>https://medium.com/@taniaosdch?source=rss-d551c261d5de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*58XWyO0QqQsc4mcQ</url>
            <title>Stories by Tania Osadcha on Medium</title>
            <link>https://medium.com/@taniaosdch?source=rss-d551c261d5de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 15:20:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@taniaosdch/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Confusing These Two: Standard Deviation vs Standard Error]]></title>
            <link>https://taniaosdch.medium.com/stop-confusing-these-two-standard-deviation-vs-standard-error-3e781f12571c?source=rss-d551c261d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e781f12571c</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[standard-deviation]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Tania Osadcha]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 15:51:30 GMT</pubDate>
            <atom:updated>2026-09-12T15:51:30.760Z</atom:updated>
            <content:encoded><![CDATA[<p>Standard error and standard deviation are both measures related to the spread of data values, but they serve different purposes and are used in different contexts.</p><p><strong>Standard Deviation</strong> is a measure of the amount of variation or dispersion in a set of values. It tells you how spread out the data points are around the mean of the data. A high standard deviation means that the data points are more spread out from the mean, and a low standard deviation means they are closer to the mean.</p><p><strong>Standard Error</strong>, on the other hand, specifically measures the variability or dispersion of sample means around the true population mean. It is essentially the<strong> standard deviation of the sampling distribution of the mean</strong>. The standard error gives you an idea of how accurate your estimate of the mean is likely to be.</p><p>The formula for standard error (SE) of the mean involves the standard deviation (SD) of the dataset divided by the square root of the sample size (n):</p><p>SE = SD / √n</p><h4>A concrete example:</h4><blockquote>If a company has 100 employees with salaries that have a SD of $10,000, and you sample 25 of them, your SE is $10,000 / √25 = $2,000. That $2,000 is how much your sample average might drift from the true company average — what you’d get if you included all 100 employees.</blockquote><p>So, while standard deviation is used to understand the variability of individual data points within a sample, standard error is used to understand how much the sample mean of these data points would vary from the actual population mean if you were to repeat the study multiple times with different samples. This is particularly important in statistics when making inferences about a population from a sample.</p><h4>Summary</h4><p>Standard deviation describes the range of individual outcomes in your data. Standard error tells you how much to trust the average you’re reporting a small standard error means your finding is likely to hold up even with a different dataset.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e781f12571c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Sum of Squares Types in Unbalanced ANOVA]]></title>
            <link>https://taniaosdch.medium.com/understanding-sum-of-squares-types-in-unbalanced-anova-29d75085914d?source=rss-d551c261d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/29d75085914d</guid>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[anova]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Tania Osadcha]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 09:48:02 GMT</pubDate>
            <atom:updated>2025-04-24T09:48:02.332Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is about the differences between Sum of Squares (SS) in unbalanced factorial ANOVA. There are three common SS: type I, II and III (the notation raised from the <em>SAS </em>User’s Guide)<a href="https://support.sas.com/documentation/onlinedoc/stat/930/introglmest.pdf">¹</a></p><p>When the dataset is balanced, all three types give the same results for each factor. So that the <em>p</em>-value, which is influenced by SS, will be the same for each factor variable. But in unbalanced datasets, which occure more often in the real world, <em>p</em>-values will be different, depending on a Sum of Squares type.</p><h3>Example</h3><p>Imagine that we have dependent variable Y with variance 68.48067 and two factors X1 and X2. The question is what percentage of Y’s variance those two factors explain?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*BtLEtgoGLMe6Rbun093iGQ.png" /></figure><p>It depends on what kind of question you aim to ask:</p><p>1. What is the effect of X1 on Y, <strong>controlling</strong> for X2?</p><p>Or</p><p>2. What is the effect of X1 on Y, <strong>ignoring</strong> X2?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*l7ay_sDEZUvo6MLbq1HGkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*z7ivvjnBBjNP2GB-B6SfeQ.png" /><figcaption>Fig.2. controlling for X2 (left), ingnoring X2 (right).</figcaption></figure><h4>Type I</h4><p>The percentage of variability of Y that factor explains, depends on the order in which it has been added to the model.</p><p>If we are adding X1 first, than it <strong>ignores </strong>X2. Meaning that it explains it’s variability and the shared variability with X2 <strong>SS(X1)</strong>. And if we then would add X2 it would explain part of Y’s variability, accounting for the amount X1 has already explained <strong>SS(X2|X1).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*u7b6-k1NqxPEKlgFkr9-yA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*ex15ZTebBL6SOdpqvgbOoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*ft2Oi_l88vdhuhTBMxLElQ.png" /><figcaption>Fig. 3. Type I SS</figcaption></figure><p>In both cases, SS for all the effects add up to the total SS sum (the total variation of the dependent variable). Which is not the case for other SS types.</p><p>Type I here is mostly for the illustrational purposes as it is not usefull for the factorial design.</p><h4>Type II</h4><p>Type II SS for each main effect is considered as if they were added after the other main effects but <em>before</em> the interaction.</p><p>Type II SS calculates each main effect, adjusted for the presence of the other main effect, but not the interaction <strong>SS(X1|X2) </strong>and <strong>SS(X2|X1)</strong>. So they are refered to the second line in Type I from the Fig. 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*FmbtfvPrwsAPnqxX66G8GA.png" /><figcaption>Fig. 4. Type II results</figcaption></figure><p>Notice, that sum of individual SS will no longer be equal to the total sum of squares as in Type I.</p><p>Type II SS should be used when the interaction is either <strong>non-significant</strong> or theoretically less relevant. So check for the interaction significance first.</p><h4><strong>Type III</strong></h4><p>For Type III Sum of Squares, each main effect is tested <strong>as if it was the last one added to the model</strong>: SS(X1|X2, X1*X2) and SS(X2|X1, X1*X2).</p><p>For <strong>X1,</strong> we are controlling for the other main effect <strong>X2,</strong> and for the interaction<strong> X1*X2</strong>. This if why main effects SS is smaller in Type 3 (Fig. 5) than in Type II (Fig. 4). Because some variability of <strong>Y</strong> was already explained by the other main efffect + the interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*BsLRw54D4KtvUVu2S2X3Ig.png" /><figcaption>Fig. 5: Type III SS</figcaption></figure><p>If the interaction term is significant, <strong><em>we do not test the significance of main effects in the model further</em></strong>.</p><p>Because significant interaction means that the way <strong>X1</strong> influences Y dependens on <strong>X2 </strong>values. So <strong>X1 </strong>main effect varies across levels of <strong>X2</strong>. And threfore it can not be quantified by a single value.</p><p>If the interaction term is not significant — run Type II Sum of Squares and test the main effect significance from Type II, as it is more powerful than in Type III.</p><p>This is optional — read on if you care why it’s more powerful.</p><p>More powerful means the test is less conservative, increasing the chances of rejecting the null hypothesis and detecting a significant effect when it truly exists.</p><p>This happens because the test statistic is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*umTJBELj3bl5FujjwbraYQ.png" /><figcaption>Fig. 6: Test statistics of effect significance.</figcaption></figure><p>And remember how the SS in Type III (Fig. 5) turned out smaller than in Type II (Fig. 4)? Since the SS for the effect is in the numerator of the F-statistic, the larger SS in Type II increases the F value — making it more likely to exceed the critical value and lead to rejection of the null hypothesis.</p><p>So, your step-by-step approach:</p><ol><li>Check the interaction significance using Type III SS. If it is significant use the results from the Type 3.</li><li>If the interaction is not significant — run Type II SS and test the significance of main effects.</li></ol><p>Because when the interaction is significant, we are usually no longer interested in the main effects on their own.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29d75085914d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time-dependent covariates in Cox regression]]></title>
            <link>https://taniaosdch.medium.com/time-dependent-covariates-in-cox-regression-588cee7ba102?source=rss-d551c261d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/588cee7ba102</guid>
            <category><![CDATA[kaplan-meier]]></category>
            <category><![CDATA[survival-analysis]]></category>
            <category><![CDATA[cox-regression]]></category>
            <dc:creator><![CDATA[Tania Osadcha]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 16:33:43 GMT</pubDate>
            <atom:updated>2024-11-21T16:33:43.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Cox regression assumes that each predictor’s value remains constant throughout the entire follow-up period. And these are values collected at time = 0. For example, a subject’s sex is a fixed covariate.</p><p>The idea behind time-dependent covariates is that any event or change that occurs during the follow-up period and might influence the survival rate should be included as a time-dependent covariate.</p><p>If your start time is a surgery, or diagnosis, or transplantation or whatever, then values of predictors must be collected at the time of the surgery (diagnosis or transplantation). For example, if one of your predictor is a cholesterol measurement then it must be a cholesterol value taken at the time of a surgery (time = 0). If one of your predictors is a smoking status it must the smoking status at the baseline (time = 0).</p><p>Problems arise when a predictor changes over time, and we want to include this change in the Cox model. For example, if a patient undergoes a second surgery during follow-up or if cholesterol is measured again three months after the baseline, we may want to assess how these changes impact survival.</p><p>In the presence of a variable that changes its value in time – and its new value affects the survival rate – you should include all values of such predictors in the dataset. So one subject can have more than one row.</p><p>In general, always ensure you understand what is the start time in your data and confirm that the predictor values were collected at that start time.</p><p>Let’s analyze the following dataset. It includes 50 patients who have undergone surgery, and our goal is to examine their survival rates.</p><p>The follow-up period starts at the time of the first surgery. The end of the follow-up is either the time of death (event = 1) or today’s date (event = 0).</p><pre>data %&gt;%<br>    head(15)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*03BiFPfRSFE5HxKC7Xoifg.png" /><figcaption>First 15 rows of an example data.</figcaption></figure><p>Notice how patient <strong>1</strong> has two rows. It is because he underwent the surgery twice: in 2014 and in 2016. Surgery is a time dependent covariate in our example. The second surgery, to be precise.</p><pre>data %&gt;%<br>    group_by(patient_id) %&gt;%<br>    mutate(surgery_number = as.factor(1:n()),<br>          event = as.factor(event)) %&gt;%<br>    ggplot(aes(x=date_of_surgery)) +<br>    geom_point(aes(date_of_surgery, event, col=surgery_number), size=3) +<br>    geom_vline(aes(xintercept = date_of_surgery, col = surgery_number)) +<br>    geom_vline(aes(xintercept = date_of_death), col=&#39;black&#39;,  size=1) +<br>    theme_bw() +<br>    labs(title = &#39;Follow-up period&#39;, subtitle = &#39;black line = death&#39;) +<br>    facet_wrap(~patient_id)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hATTDW5ZOuAmw2KDZ3nfbA.png" /><figcaption>Plot of surgeries for each patient during the follow-up period.</figcaption></figure><p>Of course, we could simplify the analysis by considering only the first surgery for each patient, ignoring any subsequent surgeries, and then run the Cox regression with no time-dependent covariates.</p><pre>data_for_simple_cox &lt;- data %&gt;%<br>    group_by(patient_id) %&gt;%<br>    slice_head() %&gt;% # leave only the first row for each patient.<br>    ungroup()</pre><pre>data_for_simple_cox %&gt;%<br>    head(15)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*1N_UgUEZzDtZEP2fxioGFQ.png" /></figure><p>First 15 rows are now actually equal to the first 15 patients.</p><p>Lets make a Kaplan–Meier estimator just to check the survival curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*E3ABiTVjX8QCu0UZW2Xk_g.png" /></figure><p>Results from the Cox regression model is below.</p><pre>fit &lt;- coxph(Surv(time, event) ~ sex+age+duration_of_diabetes+heart_disease, <br>                                  data_for_simple_cox)<br>summary(fit)</pre><pre>Call:<br>coxph(formula = Surv(time, event) ~ sex + age + duration_of_diabetes + <br>    heart_disease, data = data_for_simple_cox)<br><br>  n= 50, number of events= 10 <br><br>                         coef exp(coef) se(coef)      z Pr(&gt;|z|)  <br>sexMale               1.76500   5.84158  0.85076  2.075    0.038 *<br>age                  -0.03798   0.96273  0.02612 -1.454    0.146  <br>duration_of_diabetes  0.08915   1.09324  0.05628  1.584    0.113  <br>heart_disease         1.10115   3.00762  0.68294  1.612    0.107  <br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1</pre><p>By the way, let’s also verify the assumptions of the Cox regression model. We can check the proportional hazards assumption using the cox.zph() function to determine whether we are dealing with time-dependent coefficients.</p><pre>cox.zph(fit)</pre><pre>                     chisq df    p<br>sex                  0.225  1 0.64<br>age                  0.330  1 0.57<br>duration_of_diabetes 0.678  1 0.41<br>heart_disease        1.489  1 0.22<br>GLOBAL               2.786  4 0.59</pre><p>Perfect!</p><p>Just to clarify.</p><p>This is a Cox regression formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*yZ7xp3gf1dndg7ZPUGseSg.png" /><figcaption>Cox regression</figcaption></figure><p>This article is about Time-dependent covariates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*alqZwxKNGLBZemDvokjOpA.png" /><figcaption>Vector of covariates X changes in time (t).</figcaption></figure><p>Proportional hazard assumption cox.zph() checks whether a vector of coefficients <em>β</em> changes in time (<em>t</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*SXBEnF_RMwFFlIavWnVb9A.png" /><figcaption>Time-dependent coefficients.</figcaption></figure><p>But Time-dependent coefficients is not the topic of this article.</p><p>Let’s continue with time-dependent covariates.</p><blockquote>There’s a function called <a href="https://www.rdocumentation.org/packages/survival/versions/2.38-1/topics/tmerge">tmerge()</a> that can help you create a dataset with the correct structure. If there are issues with your variables, tmerge() simply won&#39;t work. Trust me, manually creating this data structure can be a real headache. Although using tmerge() might seem confusing at first, it&#39;s definitely worth the effort. In the end, it ensures your data is well-structured, allowing for accurate estimation of survival rates.</blockquote><p>Great! So, how do we use tmerge()? We&#39;ll need two datasets: one that contains a single row per subject (which we&#39;ve already prepared earlier). Now, we just apply tmerge() to this dataset.</p><pre>df_time_ind &lt;- tmerge(data1=data_for_simple_cox,<br>         data2=data_for_simple_cox,<br>         id=patient_id,<br>         event=event(time, event))</pre><p>(I am using a life-saving guide from Max Rohde blog<a href="https://maximilianrohde.com/posts/tmerge/">¹</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvEbwH1Drqq_eSPwlU6Jdg.png" /><figcaption>head(df_time_ind)</figcaption></figure><p>And the second dataset you’ll need is for the time-dependent covariate. Basically, it’s the same initial data from the beginning of this article, but with two additional columns: a binary indicator for the <strong>second surgery</strong> and the <strong>time of the second surgery</strong>.</p><pre>df_time_dep &lt;- data %&gt;%<br>    group_by(patient_id) %&gt;%<br>    mutate(second_surgery_time = as.numeric(round(abs(lag(date_of_surgery)-date_of_surgery)/365.25, 2)),<br>           second_surgery_time = ifelse(is.na(second_surgery_time), 0, second_surgery_time),<br>           second_surgery = ifelse(second_surgery_time&gt;0, 1, 0)) %&gt;%<br>    ungroup()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1qM1Swuu1rBrYoAS1a58A.png" /><figcaption>head(df_time_dep)</figcaption></figure><p>Nice! Now, combine two datasets.</p><pre>final_data &lt;- tmerge(data1=df_time_ind,<br>         data2=df_time_dep,<br>         id=patient_id,<br>         second_surgery =event(second_surgery_time, second_surgery))</pre><p>Notice that I am creating a new variable called second_surgery.</p><p>This is how your final dataset should look in order to run a Cox regression with time-dependent covariates. Instead of a single time column, you’ll have tstart and tstop to define the time intervals. Note that Patient <strong>1</strong> has two rows because they underwent a second surgery at time 1.49 (1.5 years after the initial surgery in 2014).</p><p>Sex and heart_disease are fixed covariated and surgery is a time-dependent covariate. But covariates age and duration_of_diabetes are also time dependent! For instance, Patient 1 had diabetes for one year at baseline, but by the time of the second surgery, the duration of his diabetes had changed, naturally. And, he got 1,5 years older.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*oIUzpIezZyfedfQP4F6Ehg.png" /><figcaption>final_data</figcaption></figure><p>So I will add tstart to recalculate the age and the duration of diabetes.</p><pre>final_data &lt;- final_data %&gt;%<br>    mutate(duration_of_diabetes = duration_of_diabetes + tstart,<br>           age = age + tstart)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*tFxpST9IwULezvxofSNAkg.png" /><figcaption>final_data</figcaption></figure><p>Now, this is important here to understanding why we distinguish between fixed covariates and those that change over time. In each time interval, the Cox model compares the covariate values of individuals who experienced an event with those who are still at risk (event = 0)<a href="https://stats.stackexchange.com/users/28500/edm">²</a>.</p><p>So, if we leave duration of the diatetes 1 year in the second row, it would underestimate the influence of the covariate on a survival rate. Because patient 1 did not have an event and his duration was actually longer in the second interval.</p><p>I am saying second interval because the coxph() function doesn’t bother with exact time values you specify in the tstart and tstop columns. Instead, it treats those intervals as interval 1, interval 2, and so on. Generally, the more intervals you have, the more accurate the model becomes.</p><p>This is our new output. It doesn’t differ much from the model with one row per patient, but that’s because only a few patients had a second surgery. If you have more rows per patient and multiple time-dependent covariates, you definitely should use this approach.</p><pre># Since number of rows &gt; number of patients we add + cluster(patient_id)<br>fit &lt;- coxph(Surv(tstart, tstop, event) ~ sex+age+duration_of_diabetes+heart_disease+cluster(patient_id), <br>                                          final_data)<br>summary(fit)</pre><pre>Call:<br>coxph(formula = Surv(tstart, tstop, event) ~ sex + age + duration_of_diabetes + <br>    heart_disease, data = final_data, cluster = patient_id)<br><br>  n= 65, number of events= 10 <br><br>                         coef exp(coef) se(coef) robust se      z Pr(&gt;|z|)  <br>sexMale               1.63023   5.10505  0.82482   0.81606  1.998   0.0458 *<br>age                  -0.03596   0.96468  0.02612   0.02469 -1.457   0.1452  <br>duration_of_diabetes  0.07406   1.07688  0.05598   0.04638  1.597   0.1103  <br>heart_disease         1.10905   3.03148  0.67945   0.61365  1.807   0.0707 .<br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=588cee7ba102" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Covariance structures in Mixed Models]]></title>
            <link>https://taniaosdch.medium.com/covariance-structures-in-mixed-models-1a831389ecc5?source=rss-d551c261d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a831389ecc5</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[covariance-matrix]]></category>
            <category><![CDATA[hierarchical-data]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[mixed-models]]></category>
            <dc:creator><![CDATA[Tania Osadcha]]></dc:creator>
            <pubDate>Tue, 21 May 2024 11:53:44 GMT</pubDate>
            <atom:updated>2024-05-21T11:53:44.296Z</atom:updated>
            <content:encoded><![CDATA[<p>Covariance structure in mixed models describes the variance-covariance matrix of dependent variable <strong>Y</strong><a href="https://en.wikipedia.org/wiki/Covariance_matrix"><strong>¹</strong></a>. When dealing with a hierarchical data (this is why we are using mixed models), we are introducing the random part <strong>Zu</strong> in our model. Random part describes the variation caused by the clustered structure in the data. Measurements of <strong>Y</strong> within each cluster are often correlated. Especially when dealing with longitudinal or repeated measurements data.</p><p>Choosing the correct variance-covariance matrix that would map how values of <strong>Y</strong> interact within each clustered group leads to more accurate models. If your covariance structure is too simple then you are more likely to make the type I error (getting significant results when in reality parameters are not significant).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*VrV9wluobgD0Q_5b45iP8w.png" /><figcaption>Mixed model equation</figcaption></figure><p>We are assuming dependent variable follows Normal distribution with expected value <strong>Xb</strong> and variance-covariance matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Y4JLhmHr4i8IdkdtVhYglg.png" /></figure><p>We are interested in the variance-covariance matrix structure as it is a starting point in parameters estimation.</p><h3>Example</h3><p>Imagine you are tracking the weight of patients at four different times: at the start (baseline), after 3 months, after 6 months, and after 9 months. This is an example of repeated measures design.</p><p>One way to analyze this kind of data is by using repeated measures ANOVA. However, issues can arise if there are missing data points. For instance, patients might drop out or miss some of their visits. When the data is unbalanced like this, repeated measures ANOVA might not be the best option.</p><p>In the plot below, you can see that Patient 24 and Patient 25, for example, missed the last two visits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVgi39PcigjRlgu3YPYffA.png" /></figure><h3>General form</h3><p>This is the general form of a variance-covariance matrix, where n represents the number of patients in our example. What we are interested in is the structure of each <strong>R</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*IoAjipGX_8wk_Pgs_Y3Pvg.png" /></figure><p>Here each <strong>R</strong> is a 4 × 4 matrix itself. Because each patient has 4 measurements from each visit. And the topic of this article is to describe the structure of these <strong>R</strong>.</p><p>Below is a list of some commonly used covariance structures for <strong>R </strong>and their description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*DJ5C2GQTVG1h9nFQgO_8MQ.png" /></figure><p>The following matrix structure list is organized by computational complexity.</p><h3>Compound Symmetry</h3><p>Lets start by fitting a random intercept model in <strong><em>R</em></strong>. The fixed effect in the model is <strong>time </strong>and the random part is defined by <strong>patients</strong>.</p><pre>library(nlme) # we use nlme instead of lme4 as it allows us to specify the covariance matrix structure<br><br>fit &lt;- lme(weight ~ as.factor(time), <br>          random = ~1|Patient,  <br>          data = df,<br>          method=&quot;ML&quot;)</pre><p>(Here, I am using a maximum-likelihood estimation method (<strong>ML</strong>) instead of a default <strong>REML </strong>because I am aiming to compare models with different covariance structure, which is a good practice, as you often don’t know which structure best describes variability. If you don&#39;t want to use your models for comparisons select <em>method=”REML”</em>).</p><p>When using the REML method, it separates out the variability explained by the fixed effects. This allows us to focus solely on how the random effects explain the variability in Y.</p><pre>VarCorr(fit) # to get random effects variance</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*wiPuV-bZaBeW3qByxPnSVQ.png" /><figcaption>Random intercept variance</figcaption></figure><p>Compound symmetry assumes that the variability is the same across all measurements, and the correlation between any two measurements remains constant over time or under different conditions. In other words, the correlation between two adjacent time points is the same as the correlation between the first measurement and any other measurement.</p><p><em>Be careful with this structure when you have longitudinal data (measured in time) as this structure might be too ‘simple’ and lead to type I error.</em></p><p>This is your <strong>R</strong> matrix which is the same for each patient. Remember, we are estimating diagonal elements from the general form matrix above. Thus, R1, R2, … , Rn.</p><pre>getVarCov(fit, type= &quot;marginal&quot;, individual = 1) # R1</pre><p>In this case the variance-covariance matrix <strong>R </strong>has a random intercepts variance off-diagonal and random intercepts variance (242.46) + residuals variance (6.22) on a diagonal.</p><p>Each row and column number corresponds to each time point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*FdICkYNdfAqv2cHJEfGk0Q.png" /><figcaption>Compound symmetry matrix output</figcaption></figure><p>Compound symmetry is useful if we assume that correlation between each pair of repeated measurements in the same.</p><h3>Autoregressive 1 correlation structure</h3><p>When the correlation among pairs of measures is not constant across all pairs, the residuals will not be independent of each other, potentially leading to biased result<a href="https://gamlj.github.io/mixed_example5.html">²</a>. The autoregressive 1 structure is able to deal with correlated measurements providing more accurate parameters.</p><p>The structure has homogeneous variances <em>sigma2</em> and correlation <em>rho </em>that declines exponentially with distance<a href="https://support.sas.com/resources/papers/proceedings/proceedings/sugi30/198-30.pdf">³</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*Cx0xBJpgQb913Ysl5JLmXA.png" /><figcaption>Autoregressive 1 structure</figcaption></figure><p>Basically, we are computing one correlation coefficient <em>rho </em>and then raising it to the power of the <em>distance between time points</em>. This is why this structure assumes that the distance between two consequent time points is the same for each patient. In other words, the measurements were taken at equally-spaced times.</p><p>To get the matrix in <strong><em>R</em></strong> let’s specify the model. The only difference from the previous model is that we are adding the <em>correlation</em> parameter.</p><pre>fit2 &lt;- lme(weight ~ as.factor(time), <br>            random = ~1|Patient, <br>            correlation = corAR1(form = ~1|Patient), # AR(1)<br>            data = df,<br>            method=&quot;ML&quot;)</pre><p>Now, to get the matrix, type:</p><pre>corMatrix(fit3$modelStruct$corStruct)[[1]] </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*VbZrEd2o0E86Xm00jKQOzA.png" /><figcaption>Autoregressive 1 matrix output</figcaption></figure><p>Autoregressive structure is often used in a repeated measurements design when data was collected over time periods.</p><h3>Toeplitz</h3><p>This structure calculates t parameters, where t is the number of time points. For all neighbour time points is gives <em>sigma1</em> coefficient. Between pairs which are two time points apart it gives <em>sigma2</em>. And so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*693mDkQBpMp9KUnEzybObA.png" /><figcaption>Toeplitz structure</figcaption></figure><p>Unfortunately, packages <strong>lmer4 </strong>and <strong>nlme </strong>in <strong><em>R</em></strong> don&#39;t have this structure implemented. Instead, you are encouraged to use Autoregressive 1 structure as it is a special case of Toeplitz structure.</p><h3>Unstructured</h3><p>This structure lets each term be unique. Unlike the autoregressive model where the variance (sigma²) is uniform, here the variance and covariance are individually estimated from the data. This approach works for longitudinal data too, but it’s much more complex computationally since we have to calculate the term for each pair separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*3qFZsdwIsMTncsA96sYvWA.png" /><figcaption>UN structure</figcaption></figure><p>To specify the model with unstructured covariance matrix in <strong><em>R</em></strong> write:</p><pre>fit3 &lt;- lme(weight ~ as.factor(time), <br>          random = ~as.factor(time)|Patient,  <br>          data = df,<br>          method=&quot;ML&quot;)</pre><p>To see how the covariance matrix looks like we need to manually compute it using the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1AKHT4KWfKcy3kzUD2SNZg.png" /></figure><p>Because <em>getVarCov()</em> doesnt give the correct matrix (r can’t be negative)</p><pre>getVarCov(fit3) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*cCqqdtgjPxZhgoFj_B6gSQ.png" /><figcaption>getVarCov(fit3) — not a UN matrix</figcaption></figure><p>To apply the formula above, we need to extract sigma, D and Z matrix.</p><pre>D &lt;- getVarCov(fit2, type =&quot;random&quot;) # D<br>d &lt;- dummy_cols((metrics_fit %&gt;% filter(BID==unique(BID)[1]))$time_factor)[,-c(1,2)]<br>Z &lt;- cbind(rep(1,5), as.matrix(d)[1:5,])<br>print(Z)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*hAbyhW3_iYXUEEB8j46Azg.png" /><figcaption>Z matrix</figcaption></figure><p>And then multiply them:</p><pre>sigma(fit2)*diag(5) + (Z) %*% as.matrix(D) %*% t(Z)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*EL-lBC93MU5SXexMZ0aaXQ.png" /><figcaption>Unstructured matrix output</figcaption></figure><p>SO, after trying different matrix let’s compare three models using AIC<a href="https://en.wikipedia.org/wiki/Akaike_information_criterion">⁴</a> (Akaike information criterion).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*Ns7m8fl2fqt32cnQ8dW9hg.png" /></figure><p>The lowest AIC reveals the second model with the Autoregressive 1 structure.</p><p>To use it for the analysis we need to rewrite it, specifying <em>method=”REML”.</em></p><pre>fit2_REML &lt;- lme(weight ~ as.factor(time), <br>            random = ~1|Patient, <br>            correlation = corAR1(form = ~1|Patient), <br>            data = df,<br>            method=&quot;REML&quot;)</pre><p>[1] <a href="https://en.wikipedia.org/wiki/Covariance_matrix">Covariance matrix — Wikipedia</a></p><p>[2] <a href="https://gamlj.github.io/mixed_example5.html">Mixed Models: Autocorrelation in logitudinal data (gamlj.github.io)</a></p><p>[3] Guidelines for Selecting the Covariance Structure in Mixed Model Analysis. <a href="https://support.sas.com/resources/papers/proceedings/proceedings/sugi30/198-30.pdf">198–30.pdf (sas.com)</a></p><p>[4] <a href="https://en.wikipedia.org/wiki/Akaike_information_criterion">Akaike information criterion — Wikipedia</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a831389ecc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Philosophy of statistics]]></title>
            <link>https://taniaosdch.medium.com/philosophy-of-statistics-d5ca40c7c585?source=rss-d551c261d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5ca40c7c585</guid>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[statistical-inference]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[philosophy-of-science]]></category>
            <dc:creator><![CDATA[Tania Osadcha]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 10:15:53 GMT</pubDate>
            <atom:updated>2024-04-30T20:06:54.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEPW5HD8WtVwmiIfow1HjA@2x.jpeg" /><figcaption>Photo by Richard Stachmann on Unsplash</figcaption></figure><p><em>No finite amount of experimentation can justify general theories, — Hume.</em></p><p>These are my notes from the article written by Deborah Mayo<a href="https://errorstatistics.com/wp-content/uploads/2020/10/mayo-1980.pdf">¹</a> (1980), where the author justifies that statistics can serve as a tool for bridging the gap between philosophy and science. The text in italics are citations from the article.</p><p>Statistics hasn’t received as much attention from the philosophy of science as some other disciplines. One logical reason is that standard statistical methods can be applied automatically, and one doesn’t have to understand the foundaions of inference methods in order to use them. Still, statistics provides practical tools that can be useful for answering some questions relevant to philosophy. Integrating philosophical methods to address foundational questions in statistics can be beneficial to both philosophers, enabling them to use statistics to address applied problems, and to statisticians, providing a deeper understanding of applicable inference methods.</p><p>Imagine, there exists a function M that models the evidential strength between data and a hypothesis. <em>Typically, M is defined as measuring degrees of belief, confirmation, support, credibility, plausibility and the like.</em> Having such a function would ease the choice of the statistical inference task applied to the data, as it would be possible to verify the preference of one theory over another.</p><p>The current state of inductive logic to verify how well a theory suits the data is oversimplified.</p><p><em>The ‘old’ problem of induction arose from the empiricist principle that the </em><strong><em>acceptance and rejection</em></strong><em> of theories is to be solely the result of </em><strong><em>observation and experiment.</em></strong></p><p>The proposal is to recreate the known theory of induction based on already existing statistical induction tasks. Having such a tool to quantify how much support or evidence the data provide for a particular hypothesis and to justify the preference of some theories over others would be beneficial.</p><p>The author points out an important problem related to some “<em>criticisms raised against the standard methods (…) that are unable to perform the tasks to which they are put in science</em>”.</p><p>It is not the statistical methods used in scientific conclusions that are the problem but the lack of their justification. The methodology part should be prioritized over the results part. How many thumbs does the rule say you should have?</p><p>I believe it is a good habit to look at the data as the amount of information we have. This way, it creates space for uncertainty so that the conclusions we draw from the data can be seen as conclusions drawn from the information we possess. In my opinion, this explanation will make you view the results from a t-test at least a bit more sceptically already.</p><p>Some examples of the questions raised in the philosophy of science appear in statistics as well, albeit asked differently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcqofEvwBqdgov9tdd7eqQ.png" /><figcaption>Similarities between questions asked in philosophy of science and statistics.</figcaption></figure><p>Philosophical questions can be answered using the problems that statistics has solved. I really like the way Kempthorne (1976) defines that, <em>statistics may be seen as “applied philosophy of science.”</em></p><p>What philosophy of science can help with is to justify causal inferences established by statistical tests. The conclusion of a statistical test is usually made almost mechanically by rejecting or accepting the null hypothesis, making it somewhat black or white. This indeed leads to some criticism regarding whether statistical tests are suitable for making causal inferences.</p><p>The proposed solution is to change the formulation of the statistical test results. Imagine we are comparing two mean values where S is their difference. When one rejects the null hypothesis, it is not because the probability of observing such a difference is less than 5%, given there is no difference (given H0 is true). It is better to say that the obtained difference itself is sufficiently large for the null hypothesis to be true. This also supports why reporting the effect size nowadays is a good (even necessary) habit.</p><p>Significant results should not be perceived as proof of causality but rather as an invitation for other researchers to try to disprove them. Such a view is also the result of how one reports their findings, which is an important step in statistical reasoning.</p><p>Statistics, as an applied science, can be used in basically every field where there is data. But it is important to realize that those fields differ in how accurately the data can be measured. It is clear that the data collected in physics is considered to be relatively stable over time, and it is easier to generalize conclusions from an experiment, rather than results obtained after analyzing some data from psychology, which suffers from a higher level of uncertainty.</p><p>Different data have different levels of measurement errors, which is important to keep in mind to be more accurate with statistical inferences obtained from such data. An error is always present since the data are finite and the hypothesis one wants to test does not always match up with what one is able to observe. In other words, <em>the data can rarely be expected to agree exactly with theoretical predictions</em>. Examining applied statistical techniques across different fields can be beneficial in understanding their relation to the observed data.</p><p>A rigorous conclusion is not always beneficial for the research but can even be harmful if not justified properly by statistical reasoning (i.e., the initial planning of experiments, the gathering and modelling of data, and in the construction and evaluation of hypotheses and theories). The ideas of significance test controversy could be a subject to explore by philosophers, and their conclusions can be beneficial to the foundation of inference methods.</p><p>I believe one purposes of the article was not to make us more conservative when making conclusions from our data, but rather to expand and deepen our understanding of statistical inference proces and to gain a broader view of what the data tells us.</p><p>[1]: Deborah G. Mayo. <em>The Philosophical Relevance of Statistics.</em> <a href="https://errorstatistics.com/wp-content/uploads/2020/10/mayo-1980.pdf">mayo-1980.pdf (errorstatistics.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5ca40c7c585" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>