Generative AI and vibe coding in R&D

Tools, sensitive data and sustainability. Applications in R

María Cristina Nanton

About me

María Cristina Nanton

Developer
MinSal GCBA | The Global Health Network

Organizer at RLadies+ Buenos Aires
Contributor at RLadies+ Global

Data science in the public sector
Data-driven projects in a global health research network

… vibe coding?

There’s a new kind of coding I call “vibe coding”, where you fully give in to the vibes, embrace exponentials, and forget that the code even exists. […]

I “Accept All” always, I don’t read the diffs anymore. When I get error messages I just copy paste them in with no comment, usually that fixes it. […]

I’m building a project or webapp, but it’s not really coding - I just see stuff, say stuff, run stuff, and copy paste stuff, and it mostly works.

Andrej Karpathy, Twitter, February 2025 (emphasis mine)

If I don’t read the diffs anymore,
how do I know what it did is right?

And if the tool sees my whole project,
what is it seeing?

AI tools in R

The map

What it does Tool What the model sees
Autocomplete Copilot in RStudio The open file
Talk to models from R ellmer What you send it
Assistants in the editor gander, chores The selection and your environment
Give the model your session btw, mcptools Objects, docs, code running in your session
Agent in the terminal Claude Code The whole project

The further down, the more autonomy and the more access.

Assistants in the editor: Copilot, gander, chores

GitHub Copilot

Tools → Global Options → Copilot, enable it and connect your GitHub account

# 30-day readmission rate
# by service, only n >= 10

The comment works as a request; Tab accepts the suggestion.

gander

options(.gander_chat =
  ellmer::chat_anthropic())

Select code, use a keyboard shortcut and ask for something like “plot this”. It looks at your objects, so it uses your real column names.

chores

options(.chores_chat =
  ellmer::chat_anthropic())

Helpers for repetitive tasks: converting errors to cli, migrating tests to testthat 3, documenting with roxygen. You can write your own.

On RStudio Server or Workbench, Copilot only works if whoever runs the server enables it (copilot-enabled=1). Even here, the decision belongs to the organization.

Copilot in RStudio · gander · chores

ellmer: LLMs from R

An R package for using language models. Everything starts with a chat object, which keeps the conversation:

library(ellmer)
chat <- chat_anthropic()   # the API key goes in .Renviron

Chat

live_console(chat)
live_browser()

A chat in the R console or in the browser.

Ask from code

chat$chat("How do I add a
  subtitle in ggplot2?")

The answer streams into the console.

Keep the answer

chat <- chat_anthropic(
  echo = "none")
summary <- chat$chat(
  "Summarize this text: ...")

It comes back as text you can use in your analysis.

ellmer for analysts: from free text to data

Classify open-ended survey answers into categories:

library(ellmer)

# 1. The open-ended answers, as people wrote them
answers <- list(
  "They took three hours to see me",
  "The doctor explained everything very patiently"
)

# 2. What you want to get from each answer
categories <- type_object(
  topic = type_enum(c("waiting", "treatment", "other")),
  tone  = type_enum(c("positive", "negative"))
)

# 3. Ask a model that runs on your machine
chat <- chat_ollama(model = "llama3.2")
parallel_chat_structured(chat, answers, type = categories)

It returns a table with one row per answer and one column per category (topic, tone).

Claude Code in the RStudio or Positron terminal

  • It’s an agent: it reads the project, edits files, runs commands and checks the result
  • It opens in the Terminal tab of RStudio (or Positron), in the project folder
  • RStudio runs the code and Claude Code writes it; both work on the same files
# RStudio terminal, at the project root
claude
> Read R/cleaning.R and add testthat tests
  for the recode_service() function.
  Don't read anything in data/.

● Read(R/cleaning.R)
● Write(tests/testthat/test-cleaning.R)
● Bash(Rscript -e "testthat::test_dir('tests/testthat')")
  [ FAIL 0 | PASS 6 ]

Can I trust what it produces?

Does it make up references?

In 2023, ChatGPT made up more than half of the references it cited. With the same request, 2026 models hardly make any up, but some small models still do.

Queen, O. and Zou, J. (2026). The shelf life of LLM findings. Stanford University.
Walters, W. H. and Wilder, E. I. (2023). Fabrication and errors in the bibliographic citations generated by ChatGPT. Scientific Reports, 13, 14045.

Evaluating what it produces

Many of us who work in data analysis come from fields like sociology, psychology, political science or communication. We learned to program to answer questions, and few of us were taught to write tests.

A script that runs without errors can be computing something else:

  • a join that duplicates rows
  • NAs dropped without warning
  • the wrong denominator

Practices that help:

  • Read the diff: filters, joins, groupings
  • Ask for testthat tests on known cases
  • Compare with a result you already know
  • renv, Quarto, {targets}: to rerun the analysis and get the same result

Don’t be a “meat proxy”

By all means, prompt AI. But don’t just relay the output. Read it, understand it, validate it, and then write a response in your own words (a decent certificate that you’ve done the prior steps). Making that effort is value you can add.

Niklas Gruhn, “Don’t be a meat proxy”, August 3, 2026

Tom Fishburne, “AI-Generated Homogeneity”, marketoonist.com

What context do you need?

Before asking AI for something:

  1. Write down what you already know: what the work is for, where the data comes from and what each row represents, who else knows about it, what the constraints are, whether you have trusted code to reference.
  2. Write down what you expect: what you want to see, what you don’t want to see and what the ideal outcome would be. For yourself, not for the agent: that way iterations don’t end up shifting the goal.
  3. Write what you know into a context file (for example CLAUDE.md or AGENTS.md): data sources, history, caveats and decisions.

Sharon Wang, “What context do your AI agents actually need?”, posit::conf 2026

What data can it see?

Cloud or local

In the cloud: Claude (Anthropic), ChatGPT (OpenAI), Gemini (Google), Copilot (Microsoft/GitHub)

  • Easy to start, frontier models, lots of compute
  • Costs money (tokens or subscription) and needs internet
  • Your data travels to the provider

Open models on your own infrastructure: Llama, Gemma, gpt-oss, Mistral, Qwen, DeepSeek, via Ollama or similar

  • Data never leaves your machine or server
  • No per-use cost, works offline
  • Harder to set up, needs memory or a GPU, slower
  • For personal use your computer is enough; if other people depend on it, someone has to maintain it

To choose: cost, speed, hardware and privacy.

Based on L. D. Verde Arregoitia, LLMs in the R Space (R-Ladies Gaborone, 2025)

Before you start

The regulatory floor

  • By region: from very detailed frameworks to general regulation with no AI-specific guidance
  • Institutional: it may or may not exist
  • The absence of a rule that forbids something doesn’t make it safe or ethical

Your own floor

  1. What kind of data is it? Classify it before opening the chat: public, internal or confidential. Could someone’s identity be reconstructed?
  2. With which tool? One approved by your institution, under a contract that prohibits training on your data.
  3. Who authorized it? For patient or participant data, an ethics committee and a data agreement before you start.

Source: “Cuidado con lo que le confIAs” (in Spanish), AEPD, 2026

Where data can leak

What data?

Confidential

  • Credentials and keys: in .Renviron, in the code, in a screenshot
  • Databases and spreadsheets with personal data
  • Medical records, results, samples

Internal

  • Details about projects or the organization
  • Internal code, protocols and documents

Through where?

  • The prompt: “let me paste the table so you can help me”
  • The directory: an agent with access to the folder reads everything in it
  • The session: head(), glimpse(), an error that prints the row that failed
  • The terms of service: the provider stores what you send and, depending on the plan, trains on it
  • What the AI generates: apps with a public URL, repos with credentials inside

Examples of university policies

Harvard

  • Nothing confidential in public tools: research data, medical information, personnel records (not even for meeting minutes!)
  • With default settings, whatever you share is not private
  • Approved tools, licensed by the university, specifically for sensitive data

Penn State

  • De-identification is not foolproof: AI can infer identities
  • Metadata identifies too: file names, geolocation, dates
  • Nothing identifiable without IRB approval
  • Participants’ consent if generative AI is used to process their data

Sheffield

Working safely in an R project

What enters the context leaves your machine

Everything the model reads travels to the provider. In an R project, that can be head(patients), a readRDS("data/..."), the .Rhistory, rendered HTML with tables, the _freeze/ folder or an error that prints the row that failed.

The goal is for the model to see code, schemas and aggregate results, and never rows of data.

There are four layers for this, and each one covers what the previous one lets through:

  1. Instructions in CLAUDE.md. Easy to write, but the model may not follow them.
  2. Permissions and hooks. They block actions before they happen, but only the ones you anticipated.
  3. Architecture. The data isn’t where the agent works.
  4. Ways of working. Scripts and pipelines that return aggregates.

Defense in depth

If one layer fails, the next one stops it.

1. CLAUDE.md for an R project

# Data privacy (mandatory)

## What you can see
- Code in R/, scripts/, tests/ and the .qmd files (without rendered outputs)
- The schema of each dataset: schemas/*.yaml
- Synthetic samples: samples/*.parquet (same structure, fake data)
- Aggregate reports: reports/*.json

## What you never do
- Don't read or print anything in data/. No head(), no glimpse(), no View().
- To answer questions about the data, write a script in scripts/tmp/
  that returns ONLY aggregates with n >= 10. I run it and give you the result.
- In tests, use samples/, never real data.

## Why
This is patient data. Everything you read enters the context and leaves this machine.

Explaining why helps the model comply. Still, with personal data, complying most of the time isn’t enough.

2. Hard rules: permissions

// .claude/settings.json
{
  "permissions": {
    "deny": [
      "Read(./data/**)",
      "Read(./**/*.rds)",
      "Read(./**/*.RData)",
      "Read(./.Rhistory)",
      "Read(./_freeze/**)"
    ]
  }
}

A list of files Claude Code can’t open with its reading tool. No programming needed.

But it only stops that tool. If Claude runs a terminal command that reads the file, the rule doesn’t see it:

cat data/discharges.csv

That’s what hooks are for.

2. Hard rules: hooks

A script that Claude Code runs before every terminal command (registered in the same .claude/settings.json). This one blocks any command that mentions data/ or .csv or .rds files.

# .claude/hooks/block_data.R
event <- jsonlite::fromJSON(file("stdin"))
cmd <- event$tool_input$command %||% ""

# does it mention the data folder or data files?
if (grepl("data/|\\.csv|\\.rds", cmd)) {
  message("Blocked: ask for aggregates.")
  quit(status = 2)  # 2 = block
}
quit(status = 0)    # 0 = let through

But the hook only sees the command, not what the script it runs does:

Rscript scripts/tmp/peek.R

If peek.R opens the data and prints rows, it still gets through: the command doesn’t mention data/.

3. Keeping data away from where the agent works

my-project/
├── R/            functions       sees
├── tests/        testthat        sees
├── schemas/      types, ranges   sees
├── samples/      synthetic       sees
├── reports/      aggregates      sees
├── scripts/tmp/  throwaway       writes
└── data/         real data       not here

The agent works in a folder, a container or another machine where data/ doesn’t exist. To write correct code, the structure of the data is enough: a schema and a few synthetic rows (for example with {synthpop}).

# schemas/discharges.yaml
dataset: discharges
rows: 250000
columns:
  patient_id:     { type: character, pii: true }
  age:            { type: integer, range: [0, 105] }
  service:        { type: factor, levels: 3 }
  length_of_stay: { type: integer, missing: "~2%" }
  readmission_30d: { type: logical }

The schema says which columns there are, of what type and in what range, without showing a single real value.

4. Ask for the script, not the data

You ask for the script, telling it only which columns there are:

library(ellmer)
chat <- chat_anthropic()
chat$chat("I have a data frame `discharges` with
  columns service and readmission_30d (logical).
  Write tidyverse code that computes the
  readmission rate by service, only for groups
  with 10 or more cases.")

It returns something like this, which you run:

discharges |>
  group_by(service) |>
  summarise(n = n(), rate = mean(readmission_30d)) |>
  filter(n >= 10)
  • Writing a script for a one-off question used to take a while, and looking at the data was faster
  • Now it takes seconds, so ask for the script, review it and run it yourself
  • The model never saw a row: only the column names
  • The filter(n >= 10) is there because aggregates can also identify people: the mean of a group of one person is that person’s data

Easy for me, hard at scale

Individual project, no sensitive data

  • A CLAUDE.md, a settings.json and synthetic data take an afternoon
  • You choose the tool, the plan and the model
  • If something fails, the impact is limited and you see it

Organization with sensitive data

  • Each person has their own machine, tool and plan (free? does it train on the data?)
  • Instructions can’t be audited and local files can be changed
  • You need contracts with no training, managed configuration users can’t change, and environments where data lives separately
  • Plus budget, training and someone accountable

Questions to take to your organization

  • Are there approved AI tools? Under what contract?
  • Where does sensitive data live, and who can connect an agent to it?
  • Is there a separate environment (server, container) to run analyses on real data?
  • Who reviews what gets published: dashboards, apps, repos?
  • Is a local or suitable model available for tasks with sensitive text?
  • What material conditions do these practices need (licenses, servers, time to learn), and who funds them?

Reflections

If what you do with AI will have real impact

Any digital asset that affects people, projects or products in a research setting calls for assessing:

  • Sustainability in the medium (or short!) term: who maintains it, understands it and pays for it
  • Security, sensitivity and institutional risk
  • Your own knowledge gaps about the problem you’re tackling with AI

Where data is stored is a decision.
Is it your decision?

What value are we expected to bring
to the projects we work on?

What is worth investing time in?

Thank you!

Thanks to Milagro Teruel for “Claude para ML sin ver los datos”, which inspired the part on working safely in an R project.