1

My table is like this

family_group
col1 col2 col3
1    1    1 
1    2    NA
2    3    NA

I am trying to loop through each column header and call it in the function, so I can create a graph for each header

I tried this:

for (val in colnames(family_group))
{
  print(val)
  intermediate_tables <- count(na.omit(family_group$val))
  intermediate_frequency <-count(intermediate_tables$freq)
  plot  <- ggplot(data =intermediate_frequency, aes(x=intermediate_frequency$x, width = 0.5)) +geom_bar(aes(y=intermediate_frequency$freq), stat="identity", fill='lightgreen', color = 'green') + 
    geom_smooth(aes(y=intermediate_frequency$freq), method = 'loess') + 
    labs(x = "# of Samples in family", y = "# of families")
  plot
}

when printing val, it does show "col1", "col2", and "col3"

but then when I am trying to call family_group$val, it gives None

How do I call each column through looping?

Thanks

Norman Kuo
  • 143
  • 7

1 Answers1

1

An alternative to a for loop that you might find simpler, using the tidyverse function pivot_longer():

library(tidyverse)

family_group %>%
  pivot_longer(c(col1, col2, col3), 
               names_to = "column_name", 
               values_to = "value") %>%
  ggplot(aes(value)) +
  geom_bar() +
  facet_wrap(~ column_name)

The idea is rather than having multiple columns, all the data is reshaped into a very long but narrow dataframe. See more on SO here: How to plot all the columns of a data frame in R.

ravic_
  • 1,731
  • 9
  • 13