Function to create charts per column

Asked

Viewed 48 times

2

I’m using this code to plot age pyramids:

p_etarias <- read.csv(file "C:\\Users\\User\\Desktop\\DemandasCEInfo\\20200327_CNSAÚDE\\Piramides\\R\\p_etarias.csv", sep = ";",dec = ",", header = TRUE)

summary(p_etarias)

xy.pop<-c(p_etarias[1:16,1])
xx.pop<-c(p_etarias[17:32,1])
agelabels<-c("0-4","5-9","10-14","15-19","20-24","25-29","30-34",
             "35-39","40-44","45-49","50-54","55-59","60-64","65-69","70-74",
             "75+")
mcol<-color.id('#5882FA')
fcol<-color.id('#FE2E2E')

piramide1 <- par(mar=pyramid.plot(xy.pop,xx.pop,labels=agelabels,
                 main=" Pirâmide Etária de Anhanguera",lxcol=mcol,rxcol=fcol,
                 gap=1,show.values=FALSE, top.labels = c("Masc", "Idade", "Fem"),
                 ndig = 5, ))

What I want to do is create a function that runs this code for all the columns in my database. I wonder if it is possible for me to program this code to run in all columns by changing only the name that is there in the main argument of the pyramid_plot function, filling the pyramids and saving them. Or do I have to manually change the column number when I set the parameters xy.pop and xx.pop? There are 96 administrative districts and I want to make an age pyramid for all of them.

  • Hello Lucca, welcome to the OS in English. See Help Center for how to ask good questions, especially how to provide a verifiable minimum example.

1 answer

2


For what you want to 1) use the column name (either directly using the name or getting it by the number) and 2) store the column name in an object. You can then use a loop (inside or outside the function, according to convenience) to scroll through all columns.

How you did not post a sample of your data or function code (or package) pyramid.plot, I am creating a generic example, with random data and a function that generates and saves in a file an XY chart of each column.

p_etarias <- data.frame(a = rnorm(32, 10),
                        b = rnorm(32, 8),
                        c = rnorm(32, 12))

plotacols_xy <- function(df) {
  for (col in colnames(df)) {
    xy.pop <- df[1:16, col]
    xx.pop <- df[17:32, col]
    png(paste0('XYplot_', col, '.png'))
      plot(x = xx.pop, y = xy.pop, main = paste('Gráfico XY da coluna', col))
    dev.off()
  }
}

plotacols_xy(p_etarias)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.