在R中使用循环时无法访问列

发布于 2025-02-01 03:38:47 字数 806 浏览 4 评论 0原文

的数据集,我想循环浏览数据集

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"))
  }

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"))

BM是 请显示正确的列标题:“联系”,“ Job”等;不知道为什么BM $我返回零

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三寸金莲 2025-02-08 03:38:47

您的i是一个字符串,您不能将其与$操作员一起使用。您需要使用[][[]]

两个操作员之间存在一些细微的差异,具体取决于哪个类bm是什么以及plot_xtab期望的是什么,但是更安全的下注可能是使用bm [[i] ]在您的循环中(而不是bm $ i)。

实际上,由于看起来不像您在其他任何地方都使用列名,因此您也可以在列上迭代(bm中的i_col),然后使用i_col到位bm [[i]]

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]]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文