# 循环dplyr并创建多个数据框

`````` p1_Germ <- data %>% #p1 stands for plot 1
filter(plot==1, pos_ID<21) %>%
select(germ_bin)
``````

``````for(i in seq_along(plot)) {
data %>%
group_by(plot[[i]], pos_ID<21) %>%
select(germ_bin)
}
``````

``````plot <- c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12)
germ_bin <- c(0,0,1,0,1,0,0,1,1,0,1,1,0,1,0,1,0,1,1,0,1,0,1,0)
pos_ID <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24)
dataset <- data.frame(plot, germ_bin, pos_ID)
dataset
``````

``````library(dplyr)
library(purrr)

dataset %>%
group_split(plot) %>%
map(. %>% filter(pos_ID < 21) %>% select(germ_bin))

#[[1]]
# A tibble: 2 x 1
#  germ_bin
#     <dbl>
#1        0
#2        0

#[[2]]
# A tibble: 2 x 1
#  germ_bin
#     <dbl>
#1        1
#2        0

#[[3]]
# A tibble: 2 x 1
#  germ_bin
#     <dbl>
#1        1
#2        0
#....
``````

``````dataset %>%
filter(pos_ID < 21) %>%
group_split(plot) %>%
map(. %>% select(germ_bin))
``````

`for`循环尝试而言，您可以通过

``````unique_plot <- unique(dataset\$plot)
plot_list <- list(length = length(unique_plot))

for(i in seq_along(unique_plot)) {
plot_list[[i]] <- dataset %>%
filter(plot == unique_plot[i], pos_ID<21) %>%
select(germ_bin)
}
``````

``````lapply(split(dataset, dataset\$plot), function(x)
subset(x, pos_ID < 21, select = germ_bin, drop = FALSE))
``````

0 条评论