简体   繁体   中英

How can I use paste within an lapply function?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM