重复定义的函数最多n次

时间:2017-05-03 20:51:19

标签: r

我想知道如何修改下面的代码,重复函数最多7次。我不能使用replicate(7, func(f))因为我需要一个函数,它给了我一些选择重复次数的选项。我的意思是,这个函数询问我是否要继续。

假设

speed<-cars$speed
dist<-cars$dist
level<-c(1:50)   
f<-data.frame(speed,dist,level)
plot(speed, dist, main="Milage vs. Car Weight", 
    xlab="Weight", ylab="Mileage", pch=18, col="blue")
text(speed, dist, row.names(f), cex=0.6, pos=4, col="red")

这是我的功能

func = function(A){
id.co1 <- identify(f$speed, f$dist,labels=row.names(f), n = 2, pos = TRUE,plot = TRUE)
xy <- f[c(id.co1$ind[1],id.co1$ind[2]),]
lines(xy, col="red", lwd=5)
lm(dist~speed, xy)
abline(coef(lm(dist~speed, xy)),col="blue") 
x.co1 <- f$speed[id.co1$ind[1]:id.co1$ind[2]]
y.co1 <- f$dist[id.co1$ind[1]:id.co1$ind[2]]
m.co1 <- lm(y.co1 ~ x.co1)
}

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你想指定以交互方式重复执行函数的频率,而不是以编程方式。您可以使用readline

执行此操作
  

我需要一个能让我选择重复次数的选项

# some function
funcA <- function(){
 cat("i am funcA\n")
}
# some function that interactively repeats funcA a specified amount of times
doNTimesA <- function() {
  Ntimes <- readline("number of repeats: ")
  for (i in 1:Ntimes) funcA()
}
doNTimesA()
  

我的意思是,这个函数询问我是否要继续

funcB <- function(){
  while (TRUE) {
  cat("i am funcB\n")
  continue <- readline("again? y/n: ")
  if (tolower(continue)=="n") break
  }
  cat("funcB is done")
}
funcB()

编辑:对于您的特定情况,您可以将函数声明包装在while循环中,询问您是否要继续,如上面的示例funcB所示。更新它还存储其输出的位置:

func <- function(){
#initiate an iteration counter and an outputlist
  counter <- 1
  output <- list()
#start an infinite loop
  while (TRUE) {
#do your thing       
    id.co1 <- identify(f$speed, f$dist,labels=row.names(f), n = 2, pos = TRUE,plot = TRUE)
    xy <- f[c(id.co1$ind[1],id.co1$ind[2]),]
    lines(xy, col="red", lwd=5)
    lm(dist~speed, xy)
    abline(coef(lm(dist~speed, xy)),col="blue") 
    x.co1 <- f$speed[id.co1$ind[1]:id.co1$ind[2]]
    y.co1 <- f$dist[id.co1$ind[1]:id.co1$ind[2]]
    m.co1 <- lm(y.co1 ~ x.co1)
#store the result at counter index in the outputlist
    output[[counter]] <- list(xco =x.co1, yco=y.co1, lm =m.co1)
    counter <- counter+1
#prompt for next iteration
    continue <- readline("again? y/n: ")
#break the loop if the answer is 'n' or 'N'
    if (tolower(continue)=="n") break

  }
#return your output
  output
}

现在发生的是,每次迭代后,函数会询问您是否要重新运行该函数:continue <- readline("again? y/n: ")并检查您是否已回答Nn。如果您愿意,可以在答案上添加更多检查;如果您现在回答Nn以外的任何内容,则循环将再次运行。

如果您运行all <- func(),则在完成后,您可以使用all[[1]]all[[2]]等访问每个迭代的结果。

请注意,操作功能环境之外的对象通常不赞成,因此将初始绘图生成拉入函数会更清晰。

相关问题