Reputation: 235
I have a list df_list = (df1,df2,df3) of data frames, all of the same dimension but different column names. I am calling ggplot inside a for loop:
for(i in 1:3){
p = ggplot(df_list[[i]], aes(x=df_list[[i]][1], y=df_list[[i]][3], fill=df_list[[i]][2])) +
geom_bar(stat='identity', position='dodge')
}
However, R doesn't allow me to do this: I have to actually use the variable names, which means I can't use the loop. Any solutions?
Here is example data:
df1<-data.frame(order=c(1:3,4:6), gender=c('f','f','f','m','m','m'), count= c(10,20,30,20,25,30))
df2<-data.frame(order11=c(2:4,2:4), gender11=c('f','f','f','m','m','m'), count= c(11,21,30,21,25,30))
df3<-data.frame(order22=c(1:3,4:6), gender22=c('f','f','f','m','m','m'), count= c(10,20,31,21,25,30))
> df1
order gender count
1 1 f 10
2 2 f 20
3 3 f 30
4 4 m 20
5 5 m 25
6 6 m 30
>
Upvotes: 1
Views: 767
Reputation: 389325
Same logic but a different approach :
library(tidyverse)
df_list = lst(df1,df2,df3) #This is not a typo!!
imap(df_list, ~{
col <- names(.x)
ggplot(.x, aes(x=.data[[col[1]]], y=.data[[col[3]]], fill=.data[[col[2]]])) +
geom_col(position='dodge') +
ggtitle(paste0('Plot for ', .y))
}) -> plot_list
plot_list[[1]]
plot_list[[2]]
Upvotes: 2
Reputation: 12585
You may have different column names in your data frames, but the roles of the columns seem to be defined by their index in the data frame. For example, you want the first column in thr data frame to define x values in the plot and so on. This means you can use names()
and aes_string()
to get what you want.
First define some test data, as you haven't given us any.
library(tidyverse)
df1 <- tibble(x1=rnorm(10), y1=rnorm(10), z1=rep(c("A", "B"), each=5))
df2 <- tibble(x2=rnorm(10), y2=rnorm(10), z2=rep(c("A", "B"), each=5))
df3 <- tibble(x3=rnorm(10), y3=rnorm(10), z3=rep(c("A", "B"), each=5))
dfList <- list(df1, df2, df3)
Now solve the problem
lapply(
dfList,
function(df) {
names <- names(df)
df %>% ggplot(aes_string(x=names[1], y=names[2], colour=names[3])) + geom_point()
}
)
Giving
I've used geom_point()
and colour
rather than geom_bar()
and fill
but the same principle will apply.
Upvotes: 5