select()
在函数的末尾。
Dat <- structure(list(IndIDII = c("BHS_265", "BHS_265", "BHS_770", "BHS_770", "BHS_770", "BHS_377", "BHS_377", "BHS_377", "BHS_377"), IndYear = c("BHS_265-2015", "BHS_265-2016", "BHS_770-2016", "BHS_770-2017", "BHS_770-2018", "BHS_377-2015", "BHS_377-2016", "BHS_377-2017", "BHS_377-2018"), WintLat = c(47.6102519805014, 47.5988417247191, 42.9737859090909, 42.9712914772727, 42.9724390816327, 43.3474354347826, 43.3555934579439, 43.3519543396226, 43.3476466990291), WintLong = c(-112.720994832869, -112.708887595506, -109.039964727273, -109.036693522727, -109.050923061224, -109.482114456522, -109.444522149533, -109.45659254717, -109.489241553398)), class = "data.frame", row.names = c(NA, -9L))
library(tidyverse)
set.seed(123)
sample_2_consecutive <- function(tbl, group_col){
group_col <- enquo(group_col)
with_rownums <- tbl %>%
group_by(!!group_col) %>%
mutate(row = row_number())
rows_to_keep <- with_rownums %>%
filter(row != max(row)) %>%
sample_n(1) %>%
mutate(row2 = row + 1) %>%
gather(key, row, row, row2)
with_rownums %>%
semi_join(rows_to_keep, by = c(quo_name(quo(!!group_col)), "row")) %>%
arrange(!!group_col, row) %>%
ungroup() # %>%
# select(-row)
}
sample_2_consecutive(Dat, IndIDII)
#> # A tibble: 6 x 5
#> IndIDII IndYear WintLat WintLong row
#> <chr> <chr> <dbl> <dbl> <int>
#> 1 BHS_265 BHS_265-2015 47.6 -113. 1
#> 2 BHS_265 BHS_265-2016 47.6 -113. 2
#> 3 BHS_377 BHS_377-2017 43.4 -109. 3
#> 4 BHS_377 BHS_377-2018 43.3 -109. 4
#> 5 BHS_770 BHS_770-2016 43.0 -109. 1
#> 6 BHS_770 BHS_770-2017 43.0 -109. 2
reprex package
(第0.2.0版)。