Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over string variables in R

When programming in Stata I often find myself using the loop index in the programming. For example, I'll loop over a list of the variables nominalprice and realprice:

local list = "nominalprice realprice"
foreach i of local list {
  summarize `i'
  twoway (scatter `i' time)
  graph export "C:\TimePlot-`i'.png"
}

This will plot the time series of nominal and real prices and export one graph called TimePlot-nominalprice.png and another called TimePlot-realprice.png.

In R the method I've come up with to do the same thing would be:

clist <- c("nominalprice", "realprice")
for (i in clist) {
  e <- paste("png(\"c:/TimePlot-",i,".png\")", sep="")
  eval(parse(text=e))
  plot(time, eval(parse(text=i)))
  dev.off() 
}

This R code looks unintuitive and messy to me and I haven't found a good way to do this sort of thing in R yet. Maybe I'm just not thinking about the problem the right way? Can you suggest a better way to loop using strings?

like image 453
aTron Avatar asked Nov 02 '09 20:11

aTron


People also ask

How do I loop through a string in R?

In R "0123456789" is a character vector of length 1. If you want to iterate over the characters, you have to split the string into a vector of single characters using strsplit . Show activity on this post. Just for fun, here are a few other ways to split a string at each character.

How do I get all the characters in a string in R?

To get access to the individual characters in an R string, you need to use the substr function: str = 'string' substr(str, 1, 1) # This evaluates to 's'. For the same reason, you can't use length to find the number of characters in a string. You have to use nchar instead.

How do I loop through a vector in R?

To iterate over items of a vector in R programming, use R For Loop. For every next iteration, we have access to next element inside the for loop block.


2 Answers

As other people have intimated, this would be easier if you had a dataframe with columns named nominalprice and realprice. If you do not, you could always use get. You shouldn't need parse at all here.

clist <- c("nominalprice", "realprice")
for (i in clist) {
   png(paste("c:/TimePlot-",i,".png"), sep="")
   plot(time, get(i))
   dev.off() 
}
like image 71
Jonathan Chang Avatar answered Oct 19 '22 09:10

Jonathan Chang


If your main issue is the need to type eval(parse(text=i)) instead of ``i'`, you could create a simpler-to-use functions for evaluating expressions from strings:

e = function(expr) eval(parse(text=expr))

Then the R example could be simplified to:

clist <- c("nominalprice", "realprice")
for (i in clist) {
  png(paste("c:/TimePlot-", i, ".png", sep=""))
  plot(time, e(i))
  dev.off() 
}
like image 39
Tuure Laurinolli Avatar answered Oct 19 '22 08:10

Tuure Laurinolli