ある
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")
とします。あなたは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
それはまた、その出力を保存する場所更新:continue <- readline("again? y/n: ")
とチェックあなたがN
やn
に答えているかどうか:
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
}
今何が起こることは、あなたが機能を再実行したい場合は、すべての繰り返しの後、機能が要求していることです。あなたが望むなら、あなたはもっと答えをチェックすることができます。 N
またはn
以外は何も応答しないと、ループが再び実行されます。
あなたがall <- func()
を実行すると設定が完了した後、あなたがall[[1]]
を使用して、各イテレーション結果にアクセスすることができ、all[[2]]
など
一般的に、あなたの関数環境外でオブジェクトを操作するために眉をひそめていますのでご注意ので、希望してくださいあなたの関数に最初のプロットの生成を引きつけるためには、よりきれいになります。
再現可能な例があるようですが、「cars」は不明です。空のRスクリプトでそれを試してみてください。 – Parfait
@ Parfait、require(stats);を実行します。 (グラフィックス)を必要とすると、車のデータセットにアクセスできます。 – Marco
本当ですか?これらは基本パッケージであり、すでに使用可能であるはずです。関連するすべての 'library'または' require'行とオブジェクトの割り当てでコードを更新してください。クリーンで新しいR環境で再現性をテストします。これを頻繁に参照してください(http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – Parfait