[英]How to randomly sample dataframe (sample_n) and calculate summary statistics after using group_by, and iterate 999 times?
在基於兩個分類因素(plant_sp =植物種類和地點)對數據進行分組之后,我想對數據幀(test_df)進行重新采樣並計算數值響應變量(sp_rich)的摘要統計量(均值和標准差)。 然后,我希望此過程可以重復進行999次。 另外,我想使用多個樣本大小對數據幀進行重新采樣,並計算以上統計信息並執行迭代。
歸根結底,我真的很想將它放在dplyr / tidy框架中,因為我對這種樣式更加熟悉,但是可以接受基本的R /其他選項。
因此,這是一個示例數據幀:
test_df <- structure(list(plant_sp = c("plant_1", "plant_1", "plant_1", "plant_1", "plant_1",
"plant_1", "plant_1", "plant_1", "plant_1", "plant_1",
"plant_2", "plant_2", "plant_2", "plant_2", "plant_2",
"plant_2", "plant_2", "plant_2", "plant_2", "plant_2"),
site = c("a", "a", "a", "a", "a",
"b", "b", "b", "b", "b",
"a", "a", "a", "a", "a",
"b", "b", "b", "b", "b"),
sp_rich = c(5, 3, 5, 3, 5,
7, 8, 8, 8, 10,
1, 4, 5, 6, 3,
7, 3, 12, 12,11)),
row.names = c(NA, -20L), class = "data.frame",
.Names = c("plant_sp", "site", "sp_rich"))
# I can calculate the summary statistics for one iteration,
# and for one sample size at a time:
mean_calc <- test_df %>%
group_by(plant_sp, site) %>%
do(sample_n(., 3)) %>%
summarise(mean = mean(sp_rich),
sd = sd((sp_rich))) %>%
mutate(sample_size = n())
> mean_calc
# A tibble: 4 x 5
# Groups: plant_sp [2]
plant_sp site mean sd sample_size
<fct> <fct> <dbl> <dbl> <dbl>
1 A GHT 7 2 3
2 A PE 3.33 0.577 3
3 B GHT 3.33 1.53 3
4 B PE 1.67 0.577 3
# I can also manually perform the calculations manually for
# each sample size, and put the data together (hack):
# Do this manually for two different samples sizes
mean_calc_3 <- test_df %>%
group_by(plant_sp, site) %>%
do(sample_n(., 3)) %>%
summarise(mean = mean(sp_rich),
sd = sd((sp_rich))) %>%
mutate(sample_size = 3)
mean_calc_3
mean_calc_4 <- test_df %>%
group_by(plant_sp, site) %>%
do(sample_n(., 4)) %>%
summarise(mean = mean(sp_rich),
sd = sd((sp_rich))) %>%
mutate(sample_size = 4)
mean_calc_4
mean_calc <- bind_rows(mean_calc_3, mean_calc_4)
mean_calc <- mean_calc %>%
group_by(plant_sp, site, sample_size) %>%
arrange(sample_size, plant_sp, site)
# A tibble: 8 x 5
# Groups: plant_sp, site, sample_size [8]
plant_sp site mean sd sample_size
<fct> <fct> <dbl> <dbl> <dbl>
1 A GHT 5.67 1.53 3
2 A PE 4.33 1.53 3
3 B GHT 3.67 1.15 3
4 B PE 2 1 3
5 A GHT 6.5 2.08 4
6 A PE 4.25 1.26 4
7 B GHT 2.75 0.5 4
8 B PE 2.25 0.5 4
我真的很想自動執行跨多個樣本大小的這些計算(例如,n = 3,n = 4,在此示例中,適當的數據將具有〜5-10個不同大小的類別),然后將整個過程進行999次迭代。
mean_calc
df的結構最終是我要尋找的輸出,而不是一次計算平均值和sd,匯總統計量被計算999次並取平均值。
library(tidyverse)
...<your test_df>...
test_df %>% group_by(plant_sp, site) %>%
nest() %>%
crossing(sample_size=c(3,4,5), iter = seq(1:10)) %>%
mutate(sample_data = map2(data, sample_size, ~sample_n(.x,.y))) %>%
mutate(calc = map(sample_data,
~summarise(.,mean = mean(sp_rich),sd = sd((sp_rich))))) %>%
select(plant_sp, site, sample_size, iter, calc) %>%
unnest() %>%
group_by(plant_sp, site, sample_size) %>%
arrange(sample_size, plant_sp, site)
此處的樣本大小為c(3,4,5)
,迭代為10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.