0

I have a dataframe like this:

date_list = seq(ymd('2000-01-01'),ymd('2000-12-31'),by='day')
testframe = data.frame(Date = date_list)
testframe$ABC = rnorm(366)
testframe$DEF = rnorm(366)
testframe$GHI = seq(from = 10, to = 25, length.out = 366)
testframe$JKL = seq(from = 5, to = 45, length.out = 366)

I want to automatize the thing I am doing below. I want to plot each column from 2:4 against the time (Date). The plots should be saved in a form like p_columnname.

p_ABC = ggplot(data = testframe, aes(x = Date, y = ABC)) + 
  geom_line(color = "grey", size = 1) 

p_DEF = ggplot(data = testframe, aes(x = Date, y = DEF)) + 
  geom_line(color = "grey", size = 1) 

p_GHI = ggplot(data = testframe, aes(x = Date, y = GHI)) + 
  geom_line(color = "grey", size = 1) 

p_JKL = ggplot(data = testframe, aes(x = Date, y = JKL)) + 
  geom_line(color = "grey", size = 1) 

I tried to create a loop:

library(ggplot2)
theme_set(theme_gray()) 
for (i in colnames(testframe[2:ncol(testframe)])) {
  paste("p", i, sep = "_") = ggplot(data = testframe, aes(x = Date, y = i)) + 
    geom_line(color = "grey", size = 1) 
} 

That does not work! Any suggestions?

2 Answers 2

1

Using a combination of lapply and aes_string, we can generate a list of plots. You can then extract each component of the list by name if necessary.

plot_list <- lapply(names(testframe)[-1], 
                    FUN = function(n) 
                        ggplot(testframe, aes_string("Date", n))+geom_line())

names(plot_list) <- paste0("p_", names(testframe)[-1])

plot_list$p_ABC

If you want to stick with the for loop framework, we can use the assign function:

for(n in names(testframe)[-1]){
  assign(paste0("p_", n),
         ggplot(testframe, aes_string("Date", n))+
           geom_line())
}
Sign up to request clarification or add additional context in comments.

Comments

0

It may not be the best way to do it, but you can try with recursion.

f <- colnames(testframe)
sotc <- function(x){
if(is.na(f[x])){return()} 
else
{ assign(paste0("p_",f[x]),  
 ggplot(testframe,aes_string(f[1],f[x]))+geom_line(),envir = globalenv())}

 sotc(x+1)
  }

 sotc(2)

 p_ABC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.