在這篇關于采樣行數下限的比例的帖子中,我撰寫了一個函式(見下文),該函式接受一個包含一些組識別符號的 data.frame,將 data.frame 逐組拆分為一個串列,然后對比例和最小行數中的較大者進行采樣。
雖然這可行,但我想知道是否有一種有效的方法可以summarise將輸出拆分group_by()為串列,然后使用類似map/lapply的函式遍歷串列的元素。這個想法是將資料傳遞給group_by()然后傳遞給summarise(),我將在其中計算每組中的行數,然后使用一種if_else方法相應地對比例或最小數量進行采樣。但是,我發現這會產生各種范圍界定問題或型別沖突。例如,在同一個匯總呼叫中計數cur_group和cur_data子集似乎很有用,但我不確定如何正確使用它們。
任何人都知道如何在內部執行此操作summarise()或以其他方式避免split()在summarise()?
library(dplyr)
# Example data: 10 rows in group a, 100 in group b
df <- data.frame(x = 1:110,
y = rnorm(110),
group = c(rep("a", 10), rep("b", 100)))
# Proportion and minimum number of rows to sample
sample_prop <- 0.5
sample_min <- 8
# Group the data and split each group into a list of tibbles
df_list <- df %>% group_by(group) %>% group_split()
# Checks if the number of rows that would be sampled is below the minimum. If so,
# sample the minimum number of rows, otherwise sample the proportion. This is
# what I'm trying to do within a summarise call.
conditional_sample <- function(dat, sample_min, sample_prop) {
if (nrow(dat) * sample_prop < sample_min) {
slice_sample(dat, n = sample_min)
} else{
slice_sample(dat, prop = sample_prop)
}
}
# Apply the function to our list -- ideally this would be unecessary
# within summarise
sampled <- df_list %>%
lapply(., function(x) {
conditional_sample(x, sample_min, sample_prop)
})
bind_rows(sampled) # check out data
uj5u.com熱心網友回復:
一種簡單的方法是使用max()ofsample_min和sample_prop * n()作為樣本大小:
與slice():
library(dplyr)
sample_prop <- 0.5
sample_min <- 8
df %>%
group_by(group) %>%
slice(sample(n(), max(sample_min, floor(sample_prop * n())))) %>%
ungroup()
# A tibble: 58 × 3
x y group
<int> <dbl> <chr>
1 1 1.01 a
2 3 -0.389 a
3 4 0.559 a
4 5 -0.594 a
5 7 -0.415 a
6 8 -1.63 a
7 9 -2.27 a
8 10 -0.422 a
9 11 0.673 b
10 12 -1.23 b
# … with 48 more rows
# ? Use `print(n = ...)` to see more rows
或等效地filter():
df %>%
group_by(group) %>%
filter(row_number() %in% sample(n(), max(sample_min, floor(sample_prop * n())))) %>%
ungroup()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519559.html
標籤:r功能dplyr数据争吵
下一篇:從R中函式內的資料框中呼叫變數名
