Hello
I would like to create a for loop to automatically render the same plot for different "names" in html Rmarkdown. I believe the library used is library(tidyverse).
example <- data.frame(
number = as.numeric(c("1", "6", "12", "2", "3", "5", "53")),
variable = c("Low", "Low", "Low", "Normal", "Exaggerated", "Exaggerated", "NA"),
date = as.Date(c("1991-01-08", "1991-02-05", "1991-03-05", "1991-01-13", "1991-01-15", "1991-01-29", "NA")),
words = rep("NA", 7),
second_number = c("20", "10", "5", "100", "20", "5", "NA"),
third_number = c("20", "10", "5", "99", "20", "5", "NA"),
name = c( "Aname", "Aname", "Aname", "Cname", "Cname", "Cname", "IGNORE"),
fourth_number = c("20", "7", "5", "97", "19", "5", "NA"),
fifth_number = c("0", "0", "0", "0", "0", "0", "NA"),
sixth_number = c("0", "3", "0", "2", "1", "0", "NA"),
seventh_number = c("0", "0", "0", "0", "0", "0", "NA"),
more_words = rep("NA", 7),
eighth_number = as.numeric(c("1.0", "0.7", "0.1", "0.979", "0.950", "1.000", "NA")),
stringsAsFactors = FALSE
)
example <- example[order(example$number), ]
example_plot <- NULL
for (i in 1:length(unique(example$name))) {
example_plot[i] <- example |> filter(name == (unique(example$name))[i]) |>
ggplot(aes(date, eighth_number, group = variable,
color = variable,
show_guide = TRUE)) +
geom_point(size = 1) +
labs(title = (unique(example$name))[i], x = 'date', y = 'eighth number') +
geom_line() +
theme_bw() +
scale_x_date(date_labels = "%b %Y", date_breaks = "month") +
geom_label_repel(aes(label = format(date, format = "%b %d")),
size = 3,
hjust=0.5,
vjust=1,
angle=90,
box.padding = 0.25,
point.padding = 0.5,
segment.color = 'grey50')
print(example_plot[i])
}
Instead of generating the plots, R prints the table for each "name".
This is an issue I run into for both RStudio and RMarkdown. I get the warning message:
1: In example_plot[i] <- ggplot(filter(example, name == (unique(example$name))[i]), :
number of items to replace is not a multiple of replacement length
2: In example_plot[i] <- ggplot(filter(example, name == (unique(example$name))[i]), :
number of items to replace is not a multiple of replacement length
3: In example_plot[i] <- ggplot(filter(example, name == (unique(example$name))[i]), :
number of items to replace is not a multiple of replacement length
I would also appreciate tips to improve on errors in my for loop syntax. Thank you