循环创建直方图以检查数据是否标准化

问题描述 投票:0回答:1

我正在尝试创建一个函数,然后遍历它以节省我一些时间(时间 - 可能不再),但也使代码更加透明。

代码不打印任何东西,我看不出问题所在。

这是我使用的代码:

# 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)
}

我尝试在上面编写代码,并希望在几行代码中创建几个直方图。

r function loops histogram
1个回答
0
投票

我想我发现了错误或至少找到了问题的解决方案。

我所做的是:

column_names <- colnames(baseline_data)

然后不再使用变量的字符串名称我使用整数

variables <- column_names[c(127, 128)]

这使代码工作:)

© www.soinside.com 2019 - 2024. All rights reserved.