Properly preparing the R dataset for the thesis

Preparing an R dataset correctly for your thesis

The regression output looks plausible at first glance—until you notice that a person's age is coded as 999, missing values are included in the analysis as 0, or the same participant appears twice. Anyone who treats the preparing an R dataset for a thesis process merely as a technical intermediate step risks exactly these kinds of errors. Data preparation also determines whether your results are methodologically sound, reproducible, and convincing in the results section.

Why data preparation determines the quality of your thesis

Statistical procedures cannot repair data that is substantively flawed, inconsistent, or unclearly coded. R calculates precisely with what was imported—even if a missing value is stored as 99 or a nominal category is inadvertently interpreted as a number. This quickly leads to means, correlations, and models that are calculated correctly in form but are not professionally robust.

For a thesis, however, it is not just about the final output. Examiners expect decisions about data cleaning to be traceable: Which cases were excluded? How were missing values handled? According to what criterion were outliers checked? A good preparation therefore combines three goals: clean analysis data, transparent decisions, and code that can rerun the steps at any time.

The actual effort depends on the study design and data source. A cleanly exported online questionnaire requires different checks than routine data from a clinic, measurement data from a laboratory, or a dataset compiled by the researcher from multiple waves of data collection. The order, however, remains similar.

Preparing an R dataset for your thesis: a controlled process

Secure the original unchanged

Never work directly in the original CSV, Excel, or SPSS file. Save an unchanged raw file in a clearly named folder and perform all cleaning steps in an R script. This allows you to trace later how the analysis dataset was created from the raw data.

A practical project structure separates raw data, scripts, generated tables and figures, and cleaned data. File names should clearly reflect versions and dates. Avoid designations such as `final_final_new.csv`. Better would be something like `cleaned_data_2026-07-23.csv`.

Then import the file and get an overview before making any changes:

```r
library(readr)
library(dplyr)

raw_data <- read_csv("data/raw_dataset.csv")

glimpse(raw_data)
summary(raw_data)
```

`glimpse()` shows, among other things, variable names and data types. `summary()` helps to identify unusual minimum and maximum values, empty categories, or unexpected distributions early on. These initial checks are no substitute for expertise. A value may be statistically possible but substantively implausible.

Name variables clearly and check data types

Unclear column names such as `V12`, `Q_4_3`, or `Variable17` make further analysis unnecessarily error-prone. Name variables so that their meaning remains clear without a codebook, for example `age_years`, `group`, or `depression_score`. In addition, keep the original questionnaire designation in the codebook if it is relevant for documentation.

Data types are particularly critical. Group variables with codes 1 and 2 are not automatically metric. Treat them as factors in R if they represent categories. Dates, free-text fields, and numbers with decimal commas also often require targeted checking.

```r
data <- raw_data |>
rename(
age_years = age,
treatment_group = group
) |>
mutate(
treatment_group = factor(treatment_group,
levels = c(1, 2),
labels = c("Control", "Intervention"))
)
```

Whether the factor order is relevant depends on your analysis and presentation. In a regression, for example, it influences the reference category. This decision should be professionally justified, not arise randomly from the order in the dataset.

Make missing values, filters, and duplicate cases visible

Missing values are not simply empty cells. First, it must be clarified how they are coded: as `NA`, as empty text, as -9, 99, or as a separate response code such as "no answer". Only then can they be handled correctly.

```r
data <- data |>
mutate(across(everything(), ~ na_if(.x, 99)))

colSums(is.na(data))
```

Recoding 99 to `NA` is only correct if 99 actually stands for missing. In some scales, the same value can be a valid measurement. Therefore, always check the questionnaire, code plan, or data export before replacing codes across the board.

Next, you need pre-defined rules for inclusion in the analysis. These include incomplete consent forms, dropouts, failure to meet age criteria, implausibly short completion times, or missing values in key outcome variables. Such rules must not be developed only after looking at the desired results. Formulate them based on your study protocol, research question, and traceable methodological criteria.

Duplicate cases can be checked using a unique ID. If an ID is missing, combinations of timestamps, demographic information, and response patterns are only a clue—not reliable proof of a duplicate. Especially in anonymous surveys, caution is advised.

Professionally check plausibility and outliers

An outlier is not automatically an error and should never be removed on its own just because it changes the p-value. First, check whether there is an entry, transmission, or coding error. Then comes the professional question: Is the value possible under realistic conditions? Only then should it be decided whether the case remains, can be corrected, or should be excluded with justification.

For metric variables, descriptive statistics, histograms, and boxplots are helpful. For regression models, influential observations are also relevant, for example using Cook's Distance. The appropriate check depends on the procedure. A high blood value may be a central finding in a medical study, while an age of 999 years obviously indicates an error.

Document every change. Note the number of excluded cases, the reason, and the point in the workflow. In the methodology section of your thesis, this information can later be briefly reported; in the script, it remains fully preserved.

Create scales and generate new variables only after checking the items

Sum or mean scores must not be calculated blindly from all items. Check the direction of the items beforehand, especially for reverse-coded statements. An incorrectly recoded item can distort an entire scale. Also consider how many missing item responses are permissible for a score.

```r
data <- data |>
mutate(
item_3_r = 6 - item_3,
stress_mean = rowMeans(select(., item_1, item_2, item_3_r, item_4),
na.rm = TRUE)
)
```

With `na.rm = TRUE`, a mean is calculated even if only a single item is present. This is not meaningful in many studies. Therefore, add a minimum number of answered items or use the rule recommended in the literature for the scale. For validated instruments, the specifications of the manual take precedence over a convenient standard solution in R.

Reproducibility is more than a tidy script

A traceable script contains not only commands but also brief comments about decisions. Write down why a filter was set, a value was coded as missing, or a reference category was chosen. Save the cleaned dataset only at the end of the script and recreate it from the raw file at any time.

In addition, you should perform a final quality check: Do the case count and variable names match your analysis plan? Are the categories fully labeled? Have all relevant filters been applied? Does the analysis dataset contain only the variables needed for evaluation, sensitivity analyses, or reporting?

A common error is to perform cleaning steps manually in Excel and only document the subsequent R analysis starting from the already modified export. This saves time in the short term but prevents full reproduction. R is particularly valuable precisely when every step remains visible, verifiable, and repeatable with new data.

When methodological advice is useful

Preparation becomes complex especially with multi-wave data, nested datasets, routine clinical data, many missing values, psychometric scales, or already unusual results. The decision between case exclusion, imputation, or sensitivity analysis is also not purely a programming question. It must fit the research question, data generation, and planned procedure.

If you are unsure whether your cleaning is methodologically sound, individual R consultation can provide clarity. At Easy Statistik, trained statisticians discreetly and traceably check the data structure, preparation logic, and analysis plan. You retain control over your scientific work and receive documentation that can be used for the methodology and follow-up questions.

Ideally, prepare the research question, codebook, raw data structure, and planned analysis for an inquiry via the contact form. These documents alone make visible which decisions must be clarified before the first model. A cleanly prepared dataset is not a formality—it is the foundation for your thesis to withstand even critical questions.


Put knowledge into practice

From explanation
to your own analysis.

Would you like to know which method suits your project? We review your plans free of charge and give you a clear recommendation.

Your question deserves a personal answer.

Describe your project. We will assess free of charge what support would be right for you.

This site is protected by hCaptcha and the hCaptcha Privacy Policy and Terms of Service apply.