这是一个选项:在下面的代码中,我们使用逻辑测试来查找四天温度低于 8 的行的索引。然后我们使用map
在列表中的每个数据帧上实现这个方法。
library(tidyverse)
# Generate a list of 5 data frames to work with
set.seed(33)
dl = replicate(5, tibble(date=seq(as.Date("2021-01-01"), as.Date("2021-02-01"), by="1 day"),
temperature = 10 + cumsum(rnorm(length(date), 0, 3))),
simplify=FALSE)
# Index of row of fourth day with temperataure lower than 8
# Run this on the first data frame in the list
min(which(cumsum(dl[[1]][["temperature"]] < 8) == 4))
#> [1] 8
# Run the method on each data frame in the list
# Note that infinity is returned if no data row meets the condition
idx8 = dl %>%
map_dbl(~ min(which(cumsum(.x[["temperature"]] < 8) == 4)))
idx8
#> [1] 8 29 Inf 7 6
以下是列表中第一个数据框上说明的各个步骤:
# Logical vector returning TRUE when temperature is less than 8
dl[[1]][["temperature"]] < 8
#> [1] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE
#> [13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
#> [25] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# Cumulative number of days where temperature was less than 8
cumsum(dl[[1]][["temperature"]] < 8)
#> [1] 0 0 0 0 1 2 3 4 4 5 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7
# Index of rows for which the cumulative number of days where
# temperature was less than 8 is equal to 4
which(cumsum(dl[[1]][["temperature"]] < 8) == 4)
#> [1] 8 9
# We want the index of the first row that meets the condition
min(which(cumsum(dl[[1]][["temperature"]] < 8) == 4))
#> [1] 8
从每个数据框中获取指示的行,如果没有满足条件的行,则获取缺失值。将结果作为数据框返回:
list(dl, idx8) %>%
pmap_dfr(~ {
if(is.infinite(.y)) {
tibble(date=NA, temperature=NA)
} else {
.x %>%
slice(.y) %>%
mutate(row.index=.y) %>%
relocate(row.index)
}
},
.id="data.frame")
#> # A tibble: 5 × 4
#> data.frame row.index date temperature
#> <chr> <dbl> <date> <dbl>
#> 1 1 8 2021-01-08 7.12
#> 2 2 29 2021-01-29 -0.731
#> 3 3 NA NA NA
#> 4 4 7 2021-01-07 6.29
#> 5 5 6 2021-01-06 4.58