带有循环数据的Rscript图

Kar*_*rim 3 for-loop r

如果这个问题已经得到解答,我提前道歉,但我找不到我需要的东西.我想从名为data1.dat,data2.dat,...的文件中绘制一些结果.我设法用循环导入数据,但我无法使用循环绘制结果.仅绘制第一个数据的结果.以下是我使用的脚本:

for(i in 1:3){
  assign( paste("data", i, sep=""),
  read.table(file=paste(paste("data", i, sep=""),"_lambda.dat",sep=""),head=TRUE, sep=" "))
}

#plot
for(i in 1:3){
  if(i==1){
    plot(data.frame(data1[1], data1[2]), xlim=c(-0.2, -7), ylim=c(0.31, 0.35), yaxt="n", type="l", xlab="", ylab="",lty="solid", col="red2", lwd=4, axes=TRUE)
  } else { 
    lines(data.frame(paste("data", i, "[1]", sep=""), paste("data", i, "[2]", sep="")) ,lty="twodash", col="deepskyblue4", lwd=4)
  }
}
Run Code Online (Sandbox Code Playgroud)

问题与"其他"之后的部分有关.数据没有绘制,我也没有收到任何错误信息.

谢谢您的帮助,

Thi*_*ilo 5

几乎没有任何有意义的用途assign.使用列表可以更轻松地完成上述操作:

# Read the data by inserting each data.frame into our list.
data <- list()
for (i in 1:3) {
    data[[i]] <- data.frame(runif(10), rnorm(10)) # Replace with your call to read.table.
}

# As we are lazy, we can pre-save our styles and just use them later
ltys <- c('solid', 'twodash', 'twodash')
cols <- c('red', 'deepskyblue4', 'deepskyblue4')

# Creating the empty plot first allows us to do everything else with lines. Note that there are a ton of different ways to archive this. 
plot(NA, xlim=c(0,1), ylim=c(-2,2))
# And now we just may access the data by using the lists. 
for (i in 1:length(data)) {
    d <- data[[i]]
    lines(d[,1], d[,2], lty=ltys[i], col=cols[i], lwd=4)
}
Run Code Online (Sandbox Code Playgroud)

如果我们的目标是优雅,我们甚至可以采用完全不同的方法:

# This time we will read all data into one data.frame.
# This requires the data to be of the same form, however. 
data <- data.frame()
for (i in 1:3) {
    d <- data.frame(x=runif(10), y=rnorm(10))
    # Here is the trick: We add the index i (or a file name, or something totally different) as a separate column.
    data <- rbind(data, cbind(d, group=i))
}
# This is just to ensure that our group column is a factor.
data$group <- as.factor(data$group)

# Now, plotting could be done by various ways. Personally, I like the elegance of ggplot2. 
library(ggplot2)
qplot(x,y,data=data, col=group, geom="line")
Run Code Online (Sandbox Code Playgroud)