简体   繁体   English

循环变量名称以在 R 中绘制相似图形

[英]Loop variable names to plot similar figures in R

I want to plot similar figures by using a list of variables.我想通过使用变量列表来绘制相似的数字。

The list of variables are "wuc_above, parti_above, "see_above", "look_above". All these variables are dummies(ie, they equal to either 0 or 1)变量列表是“wuc_above、parti_above、“see_above”、“look_above”。所有这些变量都是哑元(即它们等于 0 或 1)

The code to plot the figures are:绘制数字的代码是:

pdf(file ="mypath/wuc_above.pdf")
boxplot(x1[wuc_above==1] ,x2[wuc_above==1])
dev.off()
}

I want to replace the variable "wuc_above" by "parti_above", "see_above", "look_above".我想用“parti_above”、“see_above”、“look_above”替换变量“wuc_above”。 x1, x2 are some numeric variables that scale from 0 to 7. x1、x2 是一些数值变量,范围从 0 到 7。

It works like the Stata global function.它的工作原理类似于 Stata 全局函数。 However, I didn't figure out how to achieve this in R. Could anyone help me?但是,我不知道如何在 R 中实现这一点。有人可以帮助我吗? Thanks!谢谢!

I've written sth like (of course this does not work...)我写过类似的东西(当然这行不通......)

varlist <- variable.names(wuc_above,parti_above)
for (i in varlist) {
pdf(file =paste0('"mypath/',i,'.pdf'"))
boxplot(x1[paste0(i)==1] ,x2[paste0(i)==1])
dev.off()
}

Don't iterate over variable names.不要迭代变量名。 Put the variables in a list or a data.frame and then iterate over list items or data frame columns.将变量放在listdata.frame ,然后遍历列表项或数据框列。

You haven't shared any data so this is completely untested (please make your example reproducible if you need more help), but something like this should work:您尚未共享任何数据,因此这是完全未经测试的(如果您需要更多帮助,请使您的示例可重现),但这样的事情应该可行:

varlist = list(wuc_above = wuc_above, parti_above = parti_above)
for (i in seq_along(varlist)) {
  pdf(file = paste0('mypath/', names(varlist)[i], '.pdf'))
  boxplot(x1[varlist[[i]] == 1] ,x2[varlist[[i]] == 1])
  dev.off()
}

See my answer at How to make a list of data frames for good context.请参阅我在如何制作数据框列表以获得良好上下文的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM