循环 R 中的字符串变量 [英] Loop over string variables in R

查看:53
本文介绍了循环 R 中的字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Stata 中编程时,我经常发现自己在编程中使用循环索引.例如,我将遍历变量nominalprice 和realprice 的列表:

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"
}

这将绘制名义价格和实际价格的时间序列,并导出一个名为 TimePlot-nominalprice.png 的图表和另一个名为 TimePlot-realprice.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.

在 R 中,我想出的做同样事情的方法是:

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() 
}

这个 R 代码对我来说看起来不直观和混乱,我还没有找到在 R 中做这种事情的好方法.也许我只是没有以正确的方式思考问题?你能建议一种更好的使用字符串循环的方法吗?

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?

推荐答案

正如其他人所暗示的,如果您有一个包含名为 nominalpricerealprice.如果你不这样做,你总是可以使用 get.这里根本不需要 parse.

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() 
}

这篇关于循环 R 中的字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆