How to create a function to plot with using ggplot2 and gropu_by and summerise

Hello there.
I struggle to create a function in r with using ggplot2.
random_25_2.csv (975 Bytes)

To plot, I wrote blow code

The function will plot a chart to show the senior citizen and teenager for for each region.

    teenager <- random_25 %>% group_by(Region) %>% summarise(sum_teen = sum(Total_Teenager))
    senior <- random_25 %>% group_by(Region) %>% summarise(sum_senior = sum(Total_Senior_Citizen))

t_s <- rbind(teenager$sum_teen, senior$sum_senior)
rownames(t_s) <- c("Total Teenager", "Total Senior")
colnames(t_s) <- c('Northeastern', 'North central', 'Southern', 'Western')

barplot(t_s, beside = FALSE,legend = FALSE, xlab = "region", ylab = "Population", col = 2:3)

legend("topleft",legend=rownames(t_s),pch=15,col=2:3, lwd=1:3,lty=0, bty="n") Preformatted text

when I create a function, I did like the below code.

    plot_chart <- function(x, y) {v1 <- random_25 %>% group_by(Region) %>% summarise(sum_teen = sum(x))
              v2 <- random_25 %>% group_by(Region) %>% summarise(sum_senior = sum(y))
              v1_v2 <- rbind(v1$sum_x, v2$sum_y)
              rownames(v1_v2) <- c("Total Teenager", "Total Senior")
              colnames(v1_v2) <- c('Northeastern', 'North central', 'Southern', 'Western')

              barplot(v1_v2, beside = FALSE,legend = FALSE, xlab = "region", ylab = "Population", col = 2:3)

              legend("topleft",legend=rownames(v1_v2),pch=15,col=2:3, lwd=1:3,lty=0, bty="n")
            plot_chart(Total_Teenager, Total_Senior_Citizen)

error is occurring like the code can’t find Total_Teenager in V1.

How to assign to the valuable properly?

Hi @sakanashi.shunsuke. One area that there may be a problem is with this line:

v1_v2 <- rbind(v1$sum_x, v2$sum_y)

When I go through the function step-by-step, the variable names I see for the v1 and v2 dataframes are sum_teen and sum_senior. So this might be correct syntax here:

v1_v2 <- rbind(v1$sum_teen, v2$sum_senior)

Regarding the issue that:

the code can’t find Total_Teenager in V1

Using variable names as function arguments can be tricy in R when dplyr code is used in the function. I suggest checking out this post on stackoverflow as well as this post.