Reputation: 397
Few rows of my data are like:
I am trying to write a loop program in R that takes a set of rows with similar names/values and produces the bar plots in a loop for rows with similar names/values stored in a single column "Variable_name" in R.
so far, I have tried to create a separate data table for each set of rows, filtering by row values and then passing it to ggplot.
[Works but don't want to go through this process] Tedious/Manual process:
data[is.na(data)]<-'NA' #Turning NA as a valid value so that it get's included in the bar diagram.
bar_data1 <- data %>%
filter(Variable_name == 'Gender')
ggplot(bar_data1, aes(x=Levels, y=Count, fill=Levels))+geom_bar(stat="identity")+theme_minimal()+scale_y_continuous(breaks=c(0,10,20,50,100,150))
[Want but doesn't work] I also tried this for loop:
for(i in 1:2){
print(ggplot(data, aes(x=Levels, y=Count, fill=Levels))+geom_bar(stat="identity")+theme_minimal()+scale_y_continuous(breaks=c(0,10,20,50,100,150)))
}
The issue with the loop program that I have written is that it runs forever and ultimately R stops responding. Is it running out of memory? I think there is something wrong with my loop program.
Any advice on how to make it work through the loop program?
Upvotes: 2
Views: 1333
Reputation: 2090
This is an example with mtcars. We gonna plot 3 histograms with 3 groups based on the number of cyl
of the cars:
Instead of a for loop we gonna use the purrr::map()
function :
library(tidyverse)
groups <- names(table(mtcars$cyl))
plots <- map(groups,
function(group) {
(
mtcars
%>% filter(cyl == group)
%>% ggplot(aes(hp))
+ geom_histogram()
)})
print(plots)
But if you want to plot all histograms on the same figure, use facet_wrap()
:
(
mtcars
%>% ggplot(aes(hp))
+ geom_histogram()
+ facet_wrap(~cyl)
)
Upvotes: 3
Reputation: 700
If I understood the question correctly and you want to use a for loop, you are looking at something like this (the example is untested):
for(value in names(table(data$Variable_name))){
assign(paste0("data_", value), filter(data, Variable_name == value))
ggplot(paste0("data_", value), aes(x=Levels, y=Count, fill=Levels))+
geom_bar(stat="identity")+
theme_minimal()+
scale_y_continuous(breaks=c(0,10,20,50,100,150))
}
Upvotes: 0