在 R 中循环字符串变量
在 Stata 中编程时,我经常发现自己在编程中使用循环索引。例如,我将循环访问变量nominalprice 和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 的图表。
在 R 中,我想出的做同样事情的方法是:
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 中完成此类事情的好方法。也许我只是没有以正确的方式思考这个问题?您能建议一种更好的使用字符串循环的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如其他人所暗示的,如果您有一个包含名为
nominalprice
和realprice
列的数据框,这会更容易。如果不这样做,您始终可以使用get
。您在这里根本不需要parse
。As other people have intimated, this would be easier if you had a dataframe with columns named
nominalprice
andrealprice
. If you do not, you could always useget
. You shouldn't needparse
at all here.如果您的主要问题是需要输入 eval(parse(text=i)) 而不是 ``i'`,您可以创建一个更易于使用的函数来评估字符串中的表达式:
然后 R 示例可以简化为:
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:
Then the R example could be simplified to:
使用 ggplot2 和重塑:
Using ggplot2 and reshape:
我不明白你原来的解决方案有什么特别的问题,除了我不知道你为什么使用 eval() 函数。这对我来说似乎没有必要。
您还可以使用 apply 函数,例如 lapply。这是一个工作示例。我将虚拟数据创建为
zoo()
时间序列(这不是必需的,但因为无论如何您都在使用时间序列数据):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):