Search code examples
rfor-loopmultiple-columnssjplot

Cannot access column when using for loop in R


bm is my dataset, I want to loop through the dataset, each time I take the column name and make a plot

for (i in colnames(bm)) {
  print(i)
  print(plot_xtab(bm$y,
             bm$i,
             margin = "row",
             bar.pos = "stack",
             axis.titles = "Deposit Subscription",
             legend.title = 1,
             show.values = TRUE,
             show.n = FALSE,
             geom.size = 0.5, expand.grid = TRUE, vjust = "right"))
  }

The following code works where contact is my first column title/name

print(plot_xtab(bm$y,
             bm$contact,
             margin = "row",
             bar.pos = "stack",
             axis.titles = "Deposit Subscription",
             legend.title = 1,
             show.values = TRUE,
             show.n = FALSE,
             geom.size = 0.5, expand.grid = TRUE, vjust = "right"))

And I have tested to find that the i output in the loop do shows the correct column titles: "contact", "job",etc; don't know why bm$i returns NULL


Solution

  • Your i is a string and you can't use that with the $ operator. You need to use either [] or [[]].

    There are some subtle differences between the two operators depending on what class bm is and what plot_xtab is expecting, but the safer bet is likely using bm[[i]] in your loop (instead of bm$i).

    Actually since it doesn't look like you use the column name anywhere else, you could also just iterate over the columns, for(i_col in bm) then use i_col in place of bm[[i]]