Home > Software engineering >  for loop using ggplot for longitudinal data
for loop using ggplot for longitudinal data

Time:10-27

I am trying to visualize my longtudinal data by graphs using ggplot through for loop.

for(i in colnames(dat_longC)[c(3,5:10,14,17:19,30:39)]){
print(ggplot(dat_longC, aes(x = exam, y = i, group = zz_nr))  geom_point()   
  geom_line()   xlab("Examination")   ylab(i))}
}

when I use the ggplot command in a for loop, I only get a line extending between examination times. If I use the same command on a single variable, it works and gives me trajectory graphs. What do you think could be the problem?

CodePudding user response:

Your problem is that you are using i to indicate the column. That is just an index, so it does not know what you are actually trying to plot. you really want colnames(dat_longC)[i]. Unfortunately, that will still not work because you are using a string as a variable name, which does not work for ggplot2. Instead, you will likely need !!sym(colnames(dat_longC)[i]). I can't really test without your data, but here is some example code to help guide you.

library(tidyverse)


map(colnames(mtcars)[2:4],
    \(x) ggplot(mtcars, aes(!!sym(x), mpg)) 
      geom_point() 
      ggtitle(x))
#> [[1]]

#> 
#> [[2]]

#> 
#> [[3]]

CodePudding user response:

for(i in colnames(dat_longC)[c(3,5:10,14,17:19,30:39)]){ print(ggplot(dat_longC, aes_string(x = "exam" , y = i, group = "zz_nr")) geom_point()
geom_line() xlab("Examination") ylab(i))} }

Thank you very much for your reply! I just used aes_string and added quote to the variable names and it worked out.

  • Related