Killian
Killian

Reputation: 89

Looping through variables

I have a subset of data in r like so: "Subset <- subset(x, select = c("var1" , "var2", "var3"))". Now I have two functions that create two different graphs. One is a table and the other is a bar graph. One function is "quick_table(variable_name, label, sort)" The other is created by "table.desc <- describe(as.factor(eval(parse(text = "variable"))))" and then "pandoc.table(table.desc$values)". I want to be create a for loop that loops through the three variables to create six graphs. The problem is that "quick_table" depends on variable name so "var1", "var2", "var3" and "table.desc" depends on "x$var1", "x$var2", x$var3".

My code is:

for(variable in Subset) {
variable_name <- assign(sub("x$", replacement = "", x$variable, fixed = TRUE), variable)
label <- variable_name
sort <- variable_name

print(quick_table(variable_name, label, sort)
table.desc <- describe(as.factor(eval(parse(text = "variable"))))
print(pandoc.table(table.desc$values))
}

This doesn't seem to loop through my variable list. Any ideas? Thanks in advance

Upvotes: 0

Views: 529

Answers (1)

Austin Taylor
Austin Taylor

Reputation: 162

If I'm understanding your question correctly, you can use eval(parse(text = ))) to call a variable from the string of its name.

For example, if you wanted to call the subsets of a variable, each named "x$var1", "x$var2", "x$var3", in the same for loop, you could do:

for(i in 1:3){ eval(parse(text = paste0("x$var", i))) }

This would call x$var1, x$var2, and x$var3. You could then use these calls to make any tables you want. I hope this helps!

Upvotes: 0

Related Questions