這個問題最好用一個例子來說明。
假設我有一個df帶有二進制變數的資料框b(b 的值為 0 或 1)。如何從該資料框中獲取大小為 10 的隨機樣本,以便在隨機樣本中有 2 個 b=0 的實體,以及資料框中 b=1 的 8 個實體?
現在,我知道我可以做得到df[sample(nrow(df),10,]部分答案,但這會給我亂數量的 0 和 1 實體。如何在仍隨機抽取樣本的同時指定特定數量的 0 和 1 實體?
uj5u.com熱心網友回復:
這是我如何做到這一點的一個例子......取兩個樣本并將它們組合起來。我寫了一個簡單的函式,這樣你就可以“只取一個樣本”。
使用向量:
pop <- sample(c(0,1), 100, replace = TRUE)
yoursample <- function(pop, n_zero, n_one){
c(sample(pop[pop == 0], n_zero),
sample(pop[pop == 1], n_one))
}
yoursample(pop, n_zero = 2, n_one = 8)
[1] 0 0 1 1 1 1 1 1 1 1
或者,如果您正在使用具有一些唯一索引的資料框,稱為id:
# Where d1 is your data you are summarizing with mean and sd
dat <- data.frame(
id = 1:100,
val = sample(c(0,1), 100, replace = TRUE),
d1 = runif(100))
yoursample <- function(dat, n_zero, n_one){
c(sample(dat[dat$val == 0,"id"], n_zero),
sample(dat[dat$val == 1,"id"], n_one))
}
sample_ids <- yoursample(dat, n_zero = 2, n_one = 8)
sample_ids
mean(dat[dat$id %in% sample_ids,"d1"])
sd(dat[dat$id %in% sample_ids,"d1"])
uj5u.com熱心網友回復:
這是一個建議:
首先使用 id 列創建一個 0 和 1 的樣本。然后使用條件采樣 2:8 df 并將它們系結在一起:
library(tidyverse)
set.seed(123)
df <- as_tibble(sample(0:1,size=50,replace=TRUE)) %>%
mutate(id = row_number())
df1 <- df[ sample(which (df$value ==0) ,2), ]
df2 <- df[ sample(which (df$value ==1), 8), ]
df_final <- bind_rows(df1, df2)
value id
<int> <int>
1 0 14
2 0 36
3 1 21
4 1 24
5 1 2
6 1 50
7 1 49
8 1 41
9 1 28
10 1 33
uj5u.com熱心網友回復:
library(tidyverse)
set.seed(123)
df <- data.frame(a = letters,
b = sample(c(0,1),26,T))
bind_rows(
df %>%
filter(b == 0) %>%
sample_n(2),
df %>%
filter(b == 1) %>%
sample_n(8)
) %>%
arrange(a)
a b
1 d 1
2 g 1
3 h 1
4 l 1
5 m 1
6 o 1
7 p 0
8 q 1
9 s 0
10 v 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453432.html
上一篇:如何在資料框中附加列
