Loop over string variables in R

后端 未结 4 1027
囚心锁ツ
囚心锁ツ 2021-01-31 20:51

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:

4条回答
  •  既然无缘
    2021-01-31 21:41

    I don't see what's especially wrong with your original solution, except that I don't know why you're using the eval() function. That doesn't seem necessary to me.

    You can also use an apply function, such as lapply. Here's a working example. I created dummy data as a zoo() time series (this isn't necessary, but since you're working with time series data anyway):

    # x <- some time series data
    time <- as.Date("2003-02-01") + c(1, 3, 7, 9, 14) - 1
    x <- zoo(data.frame(nominalprice=rnorm(5),realprice=rnorm(5)), time)
    lapply(c("nominalprice", "realprice"), function(c.name, x) { 
      png(paste("c:/TimePlot-", c.name, ".png", sep=""))
      plot(x[,c.name], main=c.name)
      dev.off()
    }, x=x)
    

提交回复
热议问题