R重复功能直到满足条件

use*_*868 15 r function repeat conditional-statements

我正在尝试生成一个排除某些"不良数据"的随机样本.在我对其进行采样之前,我不知道数据是否"糟糕".因此,我需要从人群中随机抽取然后进行测试.如果数据"好",那么保留它.如果数据"不好",则随机抽取另一个并测试它.我想这样做,直到我的样本大小达到25.下面是我尝试编写一个函数的简化示例.谁能告诉我我错过了什么?

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)
Run Code Online (Sandbox Code Playgroud)

flo*_*del 19

这是while循环的一般用法:

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)
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用repeat(语法糖while(TRUE))和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)
}
Run Code Online (Sandbox Code Playgroud)

哪里break让你退出repeat街区.或者,您可能必须if (x$SCORE > 0) return(x)直接退出该功能.