循环 R 中的字符串变量 [英] Loop over string variables in 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?
推荐答案
正如其他人所暗示的,如果您有一个包含名为 nominalprice
和 realprice的列的数据框,这会更容易代码>.如果你不这样做,你总是可以使用
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屋!