我正在尝试创建一个函数,然后遍历它以节省我一些时间(时间 - 可能不再),但也使代码更加透明。
代码不打印任何东西,我看不出问题所在。
这是我使用的代码:
# Generate histograms
create_histogram <- function(baseline_data, variable_name, Randomization, bin_width = 6) {
plot <- ggplot(baseline_data, aes_string(x = variable_name)) +
geom_histogram(binwidth = bin_width, color = "black", fill = "lightblue") +
facet_wrap(as.formula(paste0("~ ", Randomization))) +
theme_minimal() +
labs(title = paste0(variable_name, " Histogram by Group"),
x = variable_name,
y = "Frequency")
return(plot)
}
print(ggplot(baseline_data, aes(x = age)) +
geom_histogram(binwidth = 6, color = "black", fill = "grey") +
facet_wrap(~ Randomization) +
theme_minimal() +
labs(title = "Age Histogram by Group", x = "Age", y = "Frequency")
)
# List of variables
variables <- c("age", "BMI")
for (variable in variables) {
plot <- create_histogram(baseline_data, variable, "Randomization")
print(plot)
}
我尝试在上面编写代码,并希望在几行代码中创建几个直方图。