簡體   English   中英

在 tibble R 的截止范圍內隨機采樣

[英]Sample randomly within cutoff in tibble R

我在 R 中有一個 100 分的小標題,如下:

preds <- tibble(x=1:100, y=seq(from=0.01,to=1,by=0.01))

我想隨機抽取 20 個值小於 0.5 的觀察值。 目前,我可以通過以下方式選擇前 20 個觀察值:

number_of_likely_negatives<-20

likely_negatives <- preds %>% 
    arrange(y) %>% 
    slice(1:number_of_likely_negatives)

但是如何隨機選擇 20 個 y 值低於 0.5 的觀測值?

我們可以在slice之前filter 'y' 值

likely_negatives <- preds %>% 
    arrange(y) %>% 
    filter(y < 0.5) %>%
    slice(sample(seq(number_of_likely_negatives), 20, replace = FALSE))

我們也可以使用slice_sample

preds %>% 
   arrange(y) %>%
   filter(y < 0.5) %>% 
   slice_sample(n = number_of_likely_negatives)

您可以使用以下代碼:

library(dplyr)
sample_n(preds[preds$y < 0.5,], 20)

輸出:

# A tibble: 20 × 2
       x     y
   <int> <dbl>
 1    42  0.42
 2    18  0.18
 3    44  0.44
 4    17  0.17
 5     7  0.07
 6    38  0.38
 7    23  0.23
 8    27  0.27
 9    20  0.2 
10     6  0.06
11    35  0.35
12    11  0.11
13     9  0.09
14    34  0.34
15    30  0.3 
16    29  0.29
17    39  0.39
18     3  0.03
19    13  0.13
20    47  0.47

直接回答:

preds %>% 
  slice(
    sample.int(which(y>threshold)[1], size = number_of_likely_negatives, replace = TRUE)
  )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM