This is not a function, but creates the individual plot objects:
library(ggplot2)
chr.list <- list(
chr1 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr2 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr3 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr4 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr5 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T))
)
for (i in 1:length(chr.list)) {
assign(x = paste0('p', i),
value = ggplot(chr.list[[i]], aes(V4, colour = factor(V6))) +
geom_freqpoly(binwidth = 1, size = 0.8) +
labs(x = 'score', y = 'Number of Mutations', title = paste('Chromosome', i)) +
theme_bw()
)
}
assign() takes a character string and creates an object with that name. For example: assign(x = 'x', value = 2) creates a variable, x, with a value of 2.
########
This is a function that returns a list of the plot objects, and the names of the list elements are p1, p2, p3, etc
library(ggplot2)
chr.list <- list(
chr1 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr2 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr3 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr4 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr5 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T))
)
plot.chrs <- function(chr.list) {
## create an empty list with the same length as chr.list
plot.list <- vector(mode = 'list', length = length(chr.list))
for (i in 1:length(chr.list)) {
plot.list[[i]] <- ggplot(chr.list[[i]], aes(V4, colour = factor(V6))) +
geom_freqpoly(binwidth = 1, size = 0.8) +
labs(x = 'score', y = 'Number of Mutations',
title = paste('Chromosome', i)) +
theme_bw()
names(plot.list)[i] <- paste0('p', i)
}
return(plot.list)
}
########
This is a function that creates the plots as individual objects in your global environment:
library(ggplot2)
chr.list <- list(
chr1 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr2 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr3 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr4 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T)),
chr5 = data.frame(V4 = sample(1:100, 20), V6 = sample(1:3, 20, replace = T))
)
plot.chrs <- function(chr.list) {
plot.list <- vector(mode = 'list', length = length(chr.list))
for (i in 1:length(chr.list)) {
plot.list[[i]] <- ggplot(chr.list[[i]], aes(V4, colour = factor(V6))) +
geom_freqpoly(binwidth = 1, size = 0.8) +
labs(x = 'score', y = 'Number of Mutations',
title = paste('Chromosome', i)) +
theme_bw()
names(plot.list)[i] <- paste0('p', i)
}
return(plot.list)
}