
How to Use Python, R, and AI Assistants for M&E Data
EvalCommunity Tutorial
How to Use Python, R, and AI Assistants for M&E Data Analysis and Automation
A practical guide for monitoring, evaluation, and development professionals who want to use AI-assisted coding for data cleaning, statistical analysis, visualization, automation, and reproducible reporting.
Learning Objectives
By the end of this tutorial, learners will be able to:
- Decide when to use Python or R instead of Excel alone.
- Use AI assistants to generate and explain Python or R scripts.
- Clean M&E datasets using reproducible code.
- Calculate indicators, achievement rates, and performance status.
- Create descriptive statistics, summary tables, and charts.
- Use AI to debug code and improve documentation.
- Validate AI-generated code before using results in a report.
- Document AI-assisted analysis transparently.
Why Use Python or R for M&E?
Excel is useful for everyday monitoring tasks, but Python and R become valuable when analysis needs to be repeated, audited, scaled, or documented. A script can show exactly how the data was cleaned, which formulas were used, which records were excluded, and how charts were created.
This makes Python and R especially useful for evaluations, donor reporting, longitudinal monitoring, survey analysis, data quality checks, and reproducible evidence workflows.
Tools Used in This Tutorial
| Tool | Primary Use in M&E | Example Task |
|---|---|---|
| Python | Data cleaning, automation, statistical scripts | Clean partner reporting files and calculate achievement rates. |
| R | Statistical analysis, visualization, reproducible reporting | Analyze survey results and generate charts. |
| AI assistants | Code generation, debugging, explanation, documentation | Ask AI to create a script and explain each step. |
| Jupyter / Google Colab / RStudio | Interactive coding environments | Run analysis step by step and save outputs. |
The AI-Assisted Coding Workflow for M&E
- Define the evaluation question.
- Prepare the dataset and data dictionary.
- Ask AI to suggest a script structure.
- Generate code in small, testable steps.
- Run the code and inspect outputs.
- Ask AI to explain errors or improve the script.
- Validate calculations against manual checks.
- Create charts and summary tables.
- Document assumptions, exclusions, and AI use.
- Use only validated outputs in reporting.
1. Start with the Evaluation Question
Before asking AI to write code, define the evaluation or monitoring question. Good analysis starts with the question, not with the tool.
Example M&E Questions
- Which districts are below target?
- Which indicators improved between baseline and endline?
- Are results different by sex, age group, or location?
- Which partners submitted incomplete reporting data?
- Are there outliers that require data quality review?
- What trends are visible across reporting periods?
AI Prompt
Act as an M&E data analyst. Based on the question “Which districts are below target?”, suggest a simple Python or R analysis plan. Include data cleaning, calculations, summary tables, charts, and validation checks.
2. Prepare the Dataset and Data Dictionary
AI-generated code is only useful if the dataset is clearly structured. Before writing code, prepare the data and define what each column means.
| Column Name | Meaning | Example |
|---|---|---|
| district | Geographic reporting unit | Kukës |
| month | Reporting period | March 2026 |
| indicator | Measured result | Households reached |
| target / actual | Planned and reported results | 1000 / 820 |
AI Prompt
Review this data dictionary and suggest any missing column descriptions, possible data quality risks, and validation checks needed before analysis.
3. Ask AI to Create a Python Analysis Script
Python is useful for cleaning datasets, calculating indicators, creating automated summaries, and exporting results. AI assistants can help write the first draft of the script.
AI Prompt
Write a Python script using pandas to load an Excel file called monitoring_data.xlsx, clean column names, check missing values, calculate achievement_rate as actual divided by target, create a performance_status column, and export a summary by district.
Example Python Code
import pandas as pd
import numpy as np
df = pd.read_excel("monitoring_data.xlsx")
df.columns = (
df.columns
.str.strip()
.str.lower()
.str.replace(" ", "_")
)
missing_summary = df.isna().sum().reset_index()
missing_summary.columns = ["column", "missing_values"]
df["achievement_rate"] = np.where(
(df["target"].isna()) | (df["target"] == 0),
np.nan,
df["actual"] / df["target"]
)
df["performance_status"] = np.select(
[
df["achievement_rate"].isna(),
df["achievement_rate"] >= 1.0,
df["achievement_rate"] >= 0.8
],
["No target", "Achieved", "On track"],
default="Behind target"
)
district_summary = (
df.groupby("district", as_index=False)
.agg(
total_actual=("actual", "sum"),
total_target=("target", "sum")
)
)
district_summary["overall_achievement_rate"] = (
district_summary["total_actual"] / district_summary["total_target"]
)
df.to_excel("cleaned_monitoring_data.xlsx", index=False)
district_summary.to_excel("district_summary.xlsx", index=False)
missing_summary.to_excel("missing_values_summary.xlsx", index=False)Important
Never run AI-generated code blindly. Read the script, understand each step, test it on a copy of the data, and manually verify several calculations before using the outputs.
4. Ask AI to Create an R Analysis Script
R is widely used for statistics, survey analysis, and data visualization. It is especially useful when M&E teams need clear analytical scripts and publication-ready charts.
AI Prompt
Write an R script using tidyverse to import monitoring_data.xlsx, clean column names, calculate achievement rate, classify performance status, summarize results by district, and export the summary.
Example R Code
library(tidyverse)
library(readxl)
library(writexl)
library(janitor)
df <- read_excel("monitoring_data.xlsx") |>
clean_names()
df_clean <- df |>
mutate(
achievement_rate = if_else(
is.na(target) | target == 0,
NA_real_,
actual / target
),
performance_status = case_when(
is.na(achievement_rate) ~ "No target",
achievement_rate >= 1 ~ "Achieved",
achievement_rate >= 0.8 ~ "On track",
TRUE ~ "Behind target"
)
)
district_summary <- df_clean |>
group_by(district) |>
summarise(
total_actual = sum(actual, na.rm = TRUE),
total_target = sum(target, na.rm = TRUE),
overall_achievement_rate = total_actual / total_target,
.groups = "drop"
)
write_xlsx(df_clean, "cleaned_monitoring_data.xlsx")
write_xlsx(district_summary, "district_summary.xlsx")Good Practice
Ask AI to explain each line of code. This helps learners understand the analysis instead of copying scripts without knowing what they do.
5. Use AI to Check Data Quality
AI assistants can help create scripts for data quality review. This is useful when datasets are large or when the same checks need to be repeated every reporting period.
AI Prompts for Data Quality Scripts
- Write code to check missing values by column.
- Write code to identify duplicate records by district, indicator, and month.
- Write code to flag actual values that are more than 200% of target.
- Write code to identify negative target or actual values.
- Write code to find inconsistent indicator names.
- Create a data quality report as an Excel file.
M&E Warning
Outliers should be flagged for review, not automatically removed. A high value may be a data error, but it may also reflect real implementation results.
6. Use AI for Descriptive Statistics
Descriptive statistics help evaluators understand the distribution of results before making claims. AI can help generate scripts for counts, means, medians, minimums, maximums, and grouped summaries.
AI Prompt
Write code to calculate descriptive statistics for actual, target, and achievement_rate. Group the results by indicator and district. Include count, mean, median, minimum, maximum, and number of missing values.
M&E Warning
Descriptive statistics are not findings by themselves. They are analytical signals that need to be interpreted with context, indicator definitions, sample size, and data quality limitations.
7. Use AI to Create Charts
Python and R can generate reproducible charts. This means the same code can be reused when new data arrives, reducing manual chart editing and improving consistency.
| M&E Question | Useful Chart |
|---|---|
| Which districts are below target? | Bar chart |
| Is performance improving over time? | Line chart |
| Are there unusual values? | Scatter plot or outlier table |
| How are results distributed? | Histogram or box plot |
AI Prompt
Write Python and R code to create a bar chart showing overall achievement rate by district, sorted from lowest to highest. Use a clear title, readable labels, and export the chart as a PNG file.
Chart Validation Checklist
- Does the chart use the correct dataset?
- Is the right indicator selected?
- Is the reporting period correct?
- Are percentages calculated correctly?
- Are missing values handled transparently?
- Does the chart title avoid unsupported conclusions?
- Is the chart readable for non-technical audiences?
8. Use AI to Automate Repeated Reporting Tasks
Python and R are useful when the same analysis must be repeated every month, quarter, or reporting cycle. AI can help create scripts that refresh outputs when new data is added.
Automation Examples
- Import new partner reporting files.
- Combine several district files into one dataset.
- Check missing values and duplicates.
- Recalculate indicators and achievement rates.
- Update charts automatically.
- Export clean Excel files, CSV files, or report tables.
AI Prompt
Create a Python script that imports all Excel files from a folder called monthly_reports, combines them into one dataset, checks for missing values and duplicates, calculates achievement rates, and exports a clean summary file.
9. Use AI to Debug Code
One of the most practical uses of AI assistants is debugging. When a script fails, learners can paste the error message and ask AI to explain what went wrong.
Weak Prompt
Fix this code.
Better Prompt
I am analyzing an M&E dataset in Python. Here is my code and the error message. Explain the error in plain language, identify the line causing the issue, suggest a corrected version, and explain how I can verify that the fix worked.
Important
Do not paste sensitive beneficiary data into a general AI chat. Use mock data, anonymized examples, or only the error message where possible.
10. Validate AI-Generated Code Before Reporting
AI-generated code can be useful, but it can also contain incorrect assumptions. Before using the output in a report, validate the script and the results.
Validation Checklist
- Does the code use the correct dataset?
- Are column names matched correctly?
- Are missing values handled appropriately?
- Are zero targets handled correctly?
- Are percentages calculated from the right denominator?
- Are grouped summaries using the right aggregation method?
- Are outliers flagged but not automatically removed?
- Are charts based on validated summary tables?
- Can the results be reproduced by rerunning the script?
- Are assumptions documented clearly?
AI Prompt for Code Review
Review this Python or R script as an M&E quality assurance reviewer. Identify possible calculation errors, missing data risks, denominator issues, aggregation problems, and places where manual validation is required.
11. Use AI Responsibly with Sensitive M&E Data
M&E datasets may include sensitive information about beneficiaries, households, children, income, health, disability, migration status, protection risks, or exact location. AI-assisted coding must respect data protection rules.
Before Using AI, Ask:
- Does the dataset include names, phone numbers, ID numbers, addresses, or GPS points?
- Does it include sensitive demographic or protection information?
- Can the task be done with anonymized or sample data?
- Does organizational policy allow this type of AI-assisted analysis?
- Are donor, safeguarding, and consent requirements respected?
- Is the code stored in an approved environment?
- Who has access to the data, scripts, and outputs?
Responsible AI Reminder
Use AI to help write or explain code whenever possible, but avoid sharing sensitive raw data with AI systems unless this is explicitly approved by your organization and compliant with applicable data protection requirements.
Practical Exercise for Learners
You are an M&E officer reviewing a monthly monitoring dataset from implementing partners. The dataset includes district, month, indicator, target, actual, partner, and beneficiary group.
Task 1: Ask AI to Plan the Analysis
Act as an M&E data analyst. Create a step-by-step Python or R analysis plan for a dataset with district, month, indicator, target, actual, partner, and beneficiary group. Include data quality checks, indicator calculations, summary tables, charts, and validation steps.
Task 2: Ask AI to Generate Code
Write a Python script using pandas to clean the dataset, calculate achievement rate, classify performance status, summarize results by district and indicator, and export the outputs to Excel.
Task 3: Ask AI to Review the Code
Review this script for M&E analysis risks. Check for denominator problems, missing data issues, incorrect aggregation, unclear assumptions, and validation steps that should be added.
FAQ: Python, R, and AI Assistants for M&E
Do M&E professionals need to know coding before using AI assistants?
They do not need to be advanced programmers, but they should understand the logic of the analysis. AI can help generate code, but the evaluator must still validate the calculations and outputs.
Should I use Python or R for M&E analysis?
Python is often useful for automation, data cleaning, and integrating different files. R is widely used for statistics, visualization, and reproducible research. Either can work well if the workflow is documented and validated.
Can I use AI-generated code directly in a report?
No. AI-generated code should be reviewed, tested, and validated before results are used in a report. Every formula, chart, and summary should be checked against the source data and indicator definitions.
Can I paste beneficiary data into an AI assistant?
Not unless your organization allows it and the data protection requirements are met. In most cases, use anonymized data, mock data, or only the error message when asking AI for help.
Documenting AI Use in the Methodology
Learners should practice documenting when and how AI was used. This improves transparency and helps teams explain the role of AI in the analytical process.
Example AI-Use Disclosure
Python and R scripts were developed with support from AI coding assistants for data cleaning, formula generation, summary tables, chart creation, debugging, and documentation. All AI-generated code and outputs were reviewed by the evaluation team. Calculations were validated against the underlying dataset, indicator definitions, and source documentation before use in reporting.
Final Takeaway
Python, R, and AI assistants can help M&E professionals move from manual spreadsheet work to more reproducible, transparent, and automated analysis workflows. They can support data cleaning, statistical summaries, visualization, debugging, documentation, and repeated reporting tasks.
But AI-generated code is not automatically correct. The evaluator remains responsible for understanding the analysis, validating calculations, checking assumptions, protecting sensitive data, and ensuring that every conclusion is supported by evidence.
Continue Learning with EvalCommunity Academy
Explore practical resources for evaluators, M&E officers, development professionals, and humanitarian practitioners who want to use AI responsibly in real evaluation workflows.
