我有一個具有這種結構的資料框:
> df
factor y x
1 2 0
1 3 0
1 1 0
1 2 0
2 3 0
2 1 0
2 3 1
3 4 1
3 3 1
3 6 3
3 5 2
4 4 1
4 7 8
4 2 1
2 5 3
在實際資料集中,我有 200 行和不同的變數:幾個連續變數和一個具有 70 個級別的因子變數,每個級別最多有 4 個觀察值。
我想將我的整個資料幀隨機子采樣為 4 個相同大小的組,而每組中沒有替換,僅在因子變數中。換句話說,我希望因子變數的每個級別在每組中出現的次數不超過一次。
我嘗試了不同的解決方案。例如,我嘗試將“因子”變數分為四組而不進行替換,如下所示:
factor1 <- as.character(df$factor)
set.seed(123)
group1 <- sample(factor, 35,replace = FALSE)
factor2 <- setdiff(factor1, group1)
group2 <- sample(factor2, 35,replace = FALSE)
# and the same for "group3" and "group4"
但后來我不知道如何將組向量(group1、group2 等)與我的 df('x' 和 'y')中的其他變數相關聯。
我也試過:
group1 <- sample_n(df, 35, replace = FALSE)
但是這個解決方案也失敗了,因為我的資料框不包含重復的行。唯一重復的值在因子變數中。
最后,我嘗試使用此處針對類似問題提出的解決方案,適用于我的情況:
random.groups <- function(n.items = 200L, n.groups = 4L,
factor = rep(1L, n.items)) {
splitted.items <- split(seq.int(n.items), factor)
shuffled <- lapply(splitted.items, sample)
1L (order(unlist(shuffled)) %% n.groups)
}
df$groups <- random.groups(nrow(df), n.groups = 4)
但是,生成的 4 個組包含因子變數的重復值,因此某些內容無法正常作業。
我真的很感激任何解決這個問題的想法或建議!
uj5u.com熱心網友回復:
使用data.table稍大的資料集演示的解決方案:
library(data.table)
dt <- setorder(data.table(factor = sample(1:10, 44, TRUE), x = runif(44), y = runif(44)), factor)
numGroups <- 4L
maxFactor <- max(dt$factor)
dt2 <- setorder(
setorder(
dt[sample(1:.N, .N)], # randomly reorder the data
factor # sort by factor
)[, temp := cumsum(.I > 0), by = factor] # create a column to count the occurrence of each factor
[temp <= numGroups] # remove rows that can't go in a group due to factor exclusion
[sample(1:.N, .N) <= (.N %/% numGroups)*numGroups] # randomly remove excess rows (keep the group sizes equal)
[, grp := c(replicate(.N/numGroups, sample(1:numGroups, numGroups)))], # randomly assign each row a group
grp # sort by group for table readability
)[, temp := NULL] # remove the temporary column
uj5u.com熱心網友回復:
一種方法是按因子分組,創建因子長度的變數,按大小和長度排列。最后,您為第一行、第二行、第三行和第四行分配一個組。然后,您可以使用此變數過濾掉。
library(dplyr)
df <- data_frame(factor = c(1,1,1,1,2,2,2,3,3,3,3,4,4,4,2),
x = floor(runif(15, min=0, max=20)),
y = floor(runif(15, min=211, max=305)))
df <- df %>% group_by(factor) %>% mutate(size = length(factor)) %>% arrange(desc(size), factor) %>%
ungroup() %>% mutate(group = ifelse(row_number() %% 4 == 1, "A",
ifelse(row_number() %% 4 == 2, "B",
ifelse(row_number() %% 4 == 3, "C", "D"))))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331163.html
上一篇:由于資料框中的變數而隨機洗掉行
