make an app that can be used for simulating data. The user should specify a sample size. It should take a user specified amount of covariates for which theuser can speciy a ditribution each. The software should calclate a binary outcome variable from a formula that can be specified by the user. The data should be downloadable as a csv file containing columns for each variable generated.
Drop files here
or click to upload
library(shiny)
library(dplyr)
source("simulation_logic.R")
ui <- fluidPage(
titlePanel("Data Simulation Tool"),
sidebarLayout(
sidebarPanel(
numericInput("sample_size", "Sample Size:", value = 100, min = 1),
numericInput("n_covariates", "Number of Covariates:", value = 2, min = 1),
uiOutput("covariate_inputs"),
textInput("formula", "Outcome Formula (use x1, x2, etc.):",
value = "1 / (1 + exp(-(0.5 + 2*x1 - 1.5*x2)))"),
downloadButton("download_data", "Download Simulated Data")
),
mainPanel(
h4("Preview of Simulated Data"),
tableOutput("data_preview")
)
)
)
server <- function(input, output, session) {
output$covariate_inputs <- renderUI({
n_covs <- input$n_covariates
lapply(1:n_covs, function(i) {
div(style = "margin-bottom: 15px;",
h4(paste("Covariate", i, "(x", i, ")")),
selectInput(
paste0("dist_", i),
"Distribution:",
choices = c("Normal" = "normal",
"Uniform" = "uniform",
"Binary" = "binary")
),
uiOutput(paste0("dist_params_", i))
)
})
})
observe({
n_covs <- input$n_covariates
for(i in 1:n_covs) {
local({
local_i <- i
output[[paste0("dist_params_", local_i)]] <- renderUI({
dist <- input[[paste0("dist_", local_i)]]
switch(dist,
"normal" = list(
numericInput(paste0("mean_", local_i), "Mean:", 0),
numericInput(paste0("sd_", local_i), "SD:", 1)
),
"uniform" = list(
numericInput(paste0("min_", local_i), "Min:", 0),
numericInput(paste0("max_", local_i), "Max:", 1)
),
"binary" = list(
numericInput(paste0("prob_", local_i), "Probability of 1:", 0.5)
)
)
})
})
}
})
simulated_data <- reactive({
req(input$sample_size, input$n_covariates)
covariates <- list()
for(i in 1:input$n_covariates) {
dist <- input[[paste0("dist_", i)]]
covariates[[i]] <- switch(dist,
"normal" = rnorm(input$sample_size,
input[[paste0("mean_", i)]],
input[[paste0("sd_", i)]]),
"uniform" = runif(input$sample_size,
input[[paste0("min_", i)]],
input[[paste0("max_", i)]]),
"binary" = rbinom(input$sample_size, 1,
input[[paste0("prob_", i)]])
)
}
data <- as.data.frame(do.call(cbind, covariates))
names(data) <- paste0("x", 1:input$n_covariates)
# Generate outcome
formula_text <- input$formula
data$y <- generate_outcome(data, formula_text)
data
})
output$data_preview <- renderTable({
head(simulated_data(), 10)
})
output$download_data <- downloadHandler(
filename = function() {
paste0("simulated_data_", format(Sys.time(), "%Y%m%d_%H%M%S"), ".csv")
},
content = function(file) {
write.csv(simulated_data(), file, row.names = FALSE)
}
)
}
shinyApp(ui = ui, server = server)
Hi! I can help you with any questions about Shiny and R. What would you like to know?