我想从数据帧中随机抽取1:n行,100次(即给出2000个随机数据帧)。
我可以使用sample_n函数为10个随机行执行此操作:
ran_df <- sample_n(df, 10, replace = TRUE)
但是,如何从我的数据框中为所有可能的行数(即1行,2行,3行...... 20行)执行此操作?
我的数据框如下所示:
bird_sp plant_sp value
1 species_a plant_a 1
2 species_a plant_a 1
3 species_a plant_a 1
4 species_a plant_a 1
5 species_a plant_a 1
6 species_a plant_b 1
7 species_a plant_b 1
8 species_a plant_b 1
9 species_a plant_b 1
10 species_a plant_c 1
11 species_a plant_d 1
12 species_a plant_d 1
13 species_b plant_d 1
14 species_b plant_d 1
15 species_b plant_b 1
16 species_b plant_b 1
17 species_b plant_b 1
18 species_b plant_b 1
19 species_b plant_c 1
20 species_b plant_c 1
答案 0 :(得分:0)
@Mickey向sample_n
建议的用户lapply
,然后您可以使用bind_rows
包中的dplyr
或do.call
包中的base
将列表加入数据框。
library(dplyr)
df <- read.table(text = "bird_sp plant_sp value
1 species_a plant_a 1
2 species_a plant_a 1
3 species_a plant_a 1
4 species_a plant_a 1
5 species_a plant_a 1
6 species_a plant_b 1
7 species_a plant_b 1
8 species_a plant_b 1
9 species_a plant_b 1
10 species_a plant_c 1
11 species_a plant_d 1
12 species_a plant_d 1
13 species_b plant_d 1
14 species_b plant_d 1
15 species_b plant_b 1
16 species_b plant_b 1
17 species_b plant_b 1
18 species_b plant_b 1
19 species_b plant_c 1
20 species_b plant_c 1", header = TRUE)
# Use lapply
samples_Data <- replicate(10, lapply(1:nrow(df), function(x) sample_n(df, x, replace = T))) %>%
bind_rows(.)