0

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(i.e, they equal to either 0 or 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". x1, x2 are some numeric variables that scale from 0 to 7.

It works like the Stata global function. However, I didn't figure out how to achieve this in R. Could anyone help me? 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()
}
npk66
  • 3
  • 2
  • No it does not work starting with the first line since `variable.names` is an R function that is probably nothing like the Stata function of that name. Without knowing something about `x1` and `x2` I really cannot be more specific. Provide a sample of the data or at least the structure of your data: `str(x1)`, `str(x2)`. – dcarlson Sep 17 '20 at 20:22
  • Do you get a different result if you run `boxplot(x1[T] ,x2[T])` ? – pwilcox Sep 17 '20 at 20:26
  • "wuc_above, parti_above, "see_above", "look_above" are dummy variables (i.e, they equal to either 0 or 1). x1, x2 are some numeric variables that scale from 0 to 7. @dcarlson – npk66 Sep 17 '20 at 20:36

1 Answers1

1

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.

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.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • Thank you very much! This works. Sorry for not sharing the data. For other's reference, the x1, x2 are numeric variables that scale from 0 to 7 (integer), "wuc_above, parti_above, "see_above", "look_above" are dummy variables (i.e, they equal to either 0 or 1). – npk66 Sep 17 '20 at 21:21