You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中使用reprex包创建读取本地文件的可复现示例?

Fixing Reprex Issues with Custom Local Data

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) (replace your_data_frame with 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:07:41