如何在R中使用reprex包创建读取本地文件的可复现示例?
I get it—when your problem is super specific and built-in datasets like iris or mtcars just won’t cut it, trying to use your own local data with reprex::reprex can feel frustrating. The root issue here is that reprex runs your code in a clean, isolated R session—it doesn’t have access to the data you’ve loaded in your current working environment or local files on your machine. Here’s how to fix this:
1. Embed Your Data Directly in the Reprex
The most reliable way is to include a reproducible version of your data right in your code. Use dput() to generate the code that recreates your data frame:
- In your regular R session, run
dput(your_data_frame)(replaceyour_data_framewith your actual data object). - Copy the output from
dput()and paste it into your reprex code. This will recreate the data frame when the reprex runs.
Example:
# Recreate custom data frame your_data <- structure(list( id = c(1, 2, 3), value = c(10, 20, 30), category = c("A", "B", "A") ), class = "data.frame", row.names = c(NA, -3L)) # Your problematic code here library(dplyr) your_data %>% group_by(category) %>% summarize(mean_val = mean(value))
2. Use a Minimal Subset of Your Data
If your full dataset is large, don’t include all of it—just a small subset that still reproduces the error. You can use dplyr::slice_sample() or manually pick rows to keep the reprex concise:
# Create a minimal subset of your data mini_data <- your_full_data %>% slice_sample(n = 5) # Keep 5 random rows # Now use mini_data in your code
3. Avoid Relying on Local Files
If your data comes from a CSV or other file, don’t use read.csv("my_local_file.csv")—instead, embed the file content using read.table() with text input:
# Embed CSV data directly custom_data <- read.table(text = " id,value,category 1,10,A 2,20,B 3,30,A ", sep = ",", header = TRUE) # Your code using custom_data
Why This Works
By including the data creation code directly in your reprex, you ensure that the isolated session reprex uses has everything it needs to run your code and reproduce the error. No more missing data issues!
内容的提问来源于stack exchange,提问作者Indrajeet Patil

