在R的循环中使用变量

时间:2012-07-19 01:11:42

标签: r variables loops

我的数据列名为LABELXYZ123_river,LABELXYZ123_lake,LABELXYZ345_river,LABELXYZ345_lake等....我有一个实际变量的列表 LABELXYZ123,LABELXYZ345等...我想在单独的数字上绘制每个标签的河流和湖泊数据。我带来了那段代码,但是没有用。我认为变量的问题和它的名字。你能告诉我解决方案吗?谢谢......

data <- read.table("data.txt",header=T,row.names=1)
lst  <- c("LABELXYZ123","LABELXYZ345")
for(i in lst) {
lbl_river <- paste("data","$",LABELXYZ123,"_river",sep="")
lbl_lake <- paste("data","$",LABELXYZ123,"_lake",sep="")
allt <- c(lbl_lake,lbl_river)
png(filename=i".png")
plot(paste(lbl_river,xaxt='n',xlab="",ylab="i",type="b",col="darkgreen",lwd=3,ylim=c(min(allt),max(allt)))
lines(paste(lbl_lake,type="b",col="darkred",lwd=3)
dev.off()
}

lbl_river它实际上是data$LABELXYZ123_river

2 个答案:

答案 0 :(得分:3)

努力挽救一些东西......当策划整理出来时,还有更多的东西

data <- read.table("data.txt",header=T,row.names=1)
lst  <- c("LABELXYZ123","LABELXYZ345")
for(label_name in lst) {
  lbl_river <- data[[paste(label_name, "river", sep = "_"]]
  lbl_lake  <- data[[paste(label_name, "lake", sep = "_"]]

}

答案 1 :(得分:0)

使用mnel建议......

data <- read.table("data.txt",header=T,row.names=1)
lst  <- c("LABELXYZ123","LABELXZZ123","LABELXYZ345","LABELXYZ567","LABELXYY1234","LABELXXX123")
labs <- row.names(data)
for(i in lst) {
    png(filename=paste(i,".png",sep=""),width = 700, height = 350)
    river  <- data[[paste(i, "_river", sep = "")]]
    lake <- data[[paste(i, "_lake", sep = "")]]
    allt <- c(river,lake)
    plot(river, xaxt='n',xlab="",ylab=i,type="b",col="darkred",lwd=3,ylim=c(min(allt)*1.05,max(allt)*0.95))
    lines(lake,type="b",col="darkgreen",lwd=3)
    axis(1,at=1:16,labels=labs,las=2)
    dev.off()
}