Thank you all for looking into this! Really appreciate. With a reproduceable code, would be:
d <- data.frame(school = rep(LETTERS[1:4], times = c(25, 25, 25, 25)),
student = rep(1:25, times=c(4)),
week = seq(from = 1, to = 25, by= 5),
crit1fl = sample(0:1, n, replace = TRUE),
crit2fl = sample(0:1, n, replace = TRUE),
crit3fl = sample(0:1, n, replace = TRUE))
d2 <- d %>%
count(school, week, crit1fl) %>%
group_by(school, week) %>%
mutate(prop = n/sum(n)) %>%
arrange(school, week)
d2 %>%
ggplot(aes(x=as.factor(week), y=n, fill=crit1fl)) +
geom_bar(position='fill', stat= 'identity') +
facet_wrap(~school) +
geom_text(
aes(label=scales::percent(prop)),
position='fill', vjust=1.5, color='white',
data = d2[d2$crit1fl =='Y', ]) +
labs(title= 'Proportion of subjects meeting the citeria',
y='Proportion', x = 'Week')
And then I want to loop through crit1 through 3fl (this is a simple example, but there are many fl variables in my data) to output graph.
using {{ varname }} seems to work but not sure why only the last graph (graph using crit3fl) is output, not all critfl variables in the iteration. And {{}} doesn't work in geom_text.
It wouldn't work in:
critvars <- paste0("crit", 1:3, "fl")
for (varname in critvars) {
d2 <- d %>%
count(school, week, {{ varname }}) %>%
group_by(school, week) %>%
mutate(prop = n/sum(n)) %>%
arrange(school, week)
g <- d2 %>%
ggplot(aes(x=as.factor(week), y=n, fill= {{ varname }})) +
geom_bar(position='fill', stat= 'identity') +
facet_wrap(~school) +
# geom_text(
# aes(label=scales::percent(prop)),
# position='fill', vjust=1.5, color='white',
# data = d2[d2$crit1fl =='Y', ]) +
labs(title= 'Proportion of subjects meeting the citeria',
y='Proportion', x = 'Week')
g
}
Original question: I have variable names: crit1fl, crit2fl, ... crit10fl Would like to loop through the variable names to do an analysis.
for (i in 1:10) {
d %>%
count(school, week, critifl)
.
.
}
How do we call variable using for loop indices?