r - R重复功能,直到满足条件

标签 r function conditional-statements repeat

我正在尝试生成一个排除某些“不良数据”的随机样本。在采样之前,我不知道数据是否为“不良”数据。因此,我需要从总体中随机抽取一张,然后对其进行测试。如果数据“良好”,则保留它。如果数据“不正确”,则随机绘制另一个并进行测试。我想这样做直到我的样本量达到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)

最佳答案

这是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)
}


另一种方法是使用repeatwhile(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)
}


其中break使您退出repeat块。或者,您可以使用if (x$SCORE > 0) return(x)直接退出该功能。

关于r - R重复功能,直到满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20507247/

相关文章:

r - 将多个文本注释添加到多面 ggplot geom_histogram

r - 制作 dplyr 过程的自定义函数

MySQL 基于另一列中的值的条件计数

formatting - 在 Google 电子表格中,如何忽略条件格式中的空单元格?

r - 如何在不创建一堆新元素的情况下分配给 R 中的列表?

r - 根据 R 中的值减去或添加列值

r - 带有特定 latex 模板的书本

c - 指向函数指针数组的指针

c++ - 在另一个函数中调用随机函数

javascript - 我可以使用 args1>args2 吗? args1 : args2 statement in javascript?