gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:00:10 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com