R重复功能直到满足条件 [英] R repeat function until condition met
问题描述
我正在尝试生成排除某些不良数据"的随机样本.我不知道数据是否坏",直到我采样之后.因此,我需要从人群中随机抽取,然后进行测试.如果数据好",则保留它.如果数据不好",则随机抽取另一个数据并进行测试.我想这样做,直到我的样本量达到 25.下面是我尝试编写一个执行此操作的函数的简化示例.谁能告诉我我错过了什么?
I am trying to generate a random sample that excludes certain "bad data." I do not know whether the data is "bad" until after I sample it. Thus, I need to make a random draw from the population and then test it. If the data is "good" then keep it. If the data is "bad" then randomly draw another and test it. I would like to do this until my sample size reaches 25. Below is a simplified example of my attempt to write a function that does this. Can anyone please tell me what I am missing?
df <- data.frame(NAME=c(rep('Frank',10),rep('Mary',10)), SCORE=rnorm(20))
df
random.sample <- function(x) {
x <- df[sample(nrow(df), 1), ]
if (x$SCORE > 0) return(x)
#if (x$SCORE <= 0) run the function again
}
random.sample(df)
推荐答案
下面是 while
循环的一般用法:
Here is a general use of a while
loop:
random.sample <- function(x) {
success <- FALSE
while (!success) {
# do something
i <- sample(nrow(df), 1)
x <- df[sample(nrow(df), 1), ]
# check for success
success <- x$SCORE > 0
}
return(x)
}
另一种方法是使用 repeat
(while(TRUE)
的语法糖)和 break
:
An alternative is to use repeat
(syntactic sugar for while(TRUE)
) and break
:
random.sample <- function(x) {
repeat {
# do something
i <- sample(nrow(df), 1)
x <- df[sample(nrow(df), 1), ]
# exit if the condition is met
if (x$SCORE > 0) break
}
return(x)
}
其中 break
使您退出 repeat
块.或者,您可以让 if (x$SCORE > 0) return(x)
直接退出函数.
where break
makes you exit the repeat
block. Alternatively, you could have if (x$SCORE > 0) return(x)
to exit the function directly.
这篇关于R重复功能直到满足条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!