Reputation: 31
Hi there so simply I have a list of dataframes with names.
I want to print the names of the dataframe in plots on the x-axis using lapply.
My attempt has proved futile unfortunately.
It appears lapply functions do not like vectors so converting my current product to a readable one by lapply is highly desired.
set.seed(1:1000)
df <- as.data.frame(replicate(1, rnorm(20)))
df2 <- as.data.frame(replicate(1, rnorm(20)))
df.list <- append(df,df2)
require(reshape2)
require(ggplot2)
melt.df.list <- lapply(df.list, function(x) melt(x))
names(melt.df.list) <- c("Plot1","Plot2")
lapply(melt.df.list, function(x) ggplot(x, aes(x=value)) +
geom_histogram(aes(y=..density..), colour="black", fill="white")+
geom_density(alpha=.2, fill="#FF6666") +
labs(x =
lapply(as.character(names(melt.df.list)), function(y)
paste("Counts","(",y,")", collapse ="+")),
y = "Density") +
xlim(-5, 20))
Upvotes: 1
Views: 637
Reputation: 173577
A summary of the three main options discussed so far:
# Loop over the names instead
lapply(names(melt.df.list), function(nm) ggplot(melt.df.list[[nm]], aes(x=value)) +
geom_histogram(aes(y=..density..), colour="black", fill="white")+
geom_density(alpha=.2, fill="#FF6666") +
labs(x = paste("Counts","(",nm,")"),
y = "Density") +
xlim(-5, 20))
# Use imap
library(purrr)
imap(.x = melt.df.list,.f = ~ggplot(.x, aes(x=value)) +
geom_histogram(aes(y=..density..), colour="black", fill="white")+
geom_density(alpha=.2, fill="#FF6666") +
labs(x = paste("Counts","(",.y,")"),
y = "Density") + xlim(-5, 20))
# Just write a darn for loop ;)
for (i in seq_along(melt.df.list)){
ggplot(melt.df.list[[i]], aes(x=value)) +
geom_histogram(aes(y=..density..), colour="black", fill="white")+
geom_density(alpha=.2, fill="#FF6666") +
labs(x = paste("Counts","(",names(melt.df.list)[i],")"),
y = "Density") +
xlim(-5, 20)
}
Upvotes: 4