在R中使用循环时无法访问列
的数据集,我想循环浏览数据集
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
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 whatplot_xtab
is expecting, but the safer bet is likely usingbm[[i]]
in your loop (instead ofbm$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 usei_col
in place ofbm[[i]]