0

I want to plot some graphs and the column name is changing within a loop. I also want to apply a log2() onto this column so my plan was to do something like this:

df <- data.frame(x=c(1,2,3,4,5),
                 y.bla=c(2,3,4,5,6),
                 y.blub=c(5,4,3,2,1))
for(label in c('bla','blub')) {
  g <- ggplot(df, aes_string(x='x', y=paste0('y.', label))) + geom_point()
  print(g)
}

for(label in c('bla','blub')) {
  g <- ggplot(df, aes_string(x='x', y=log2(paste0('y.', label)))) + geom_point()
  print(g)
}

But actually, the log2 function can not handle the string.
Is there a workaround?

I want to do this within the loop and not with facet wrap or something like this, since I append these single graphs to a list of different figures.

1 Answer 1

2

There's probably a few ways of doing this. I'd extract elements from the dataframe by name and transform them before plotting.

for(label in c('bla','blub')) {

  temp_var <- log2(df[[paste0('y.', label)]])

  g <- ggplot(df, aes(x=x, y= temp_var)) + geom_point()
  print(g)
}   
Sign up to request clarification or add additional context in comments.

1 Comment

Hah, that was to easy! I expected R will complain because it is no data frame or something... Love it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.