我有一个包含 106 个小标题的列表,每个小标题包含两列(日期、温度),其中包含数千个值。
我尝试创建一个函数,该函数允许我通过 tibble 获取四次温度低于 8.0 的行的索引。
我遇到的问题是我的代码只执行每个小节的第一行。
在这里你可以看到代码:
pos_r = 0;
temp =0;
posx = vector();
for (i in seq_along(data_sensor)){
if (temp < 4){
pos_r = pos_r + 1;
if (data_sensor[[i]]$Temperature < 8.0){
temp=temp+1;
} else if (temp == 4){
posx[i] = pos_r;
i = i+1;
}
}
}
> [1] NA NA NA NA NA NA 5 6 NA 7 8 NA NA 9 NA NA NA 10 11 NA 12 13 14 NA 15 16 17 18 19 NA
[31] 20 21 22 NA 23 24 25 26 27 NA 28 NA 29 30 NA 31 32 33 34 NA 35 36 37 38 NA 39 40 41 42 43
[61] 44 NA 45 NA 46 47 48 49 50 51 52 53 54 55 56 57 58 NA NA NA 59 60 61 NA 62 63 NA 64 65 66
[91] NA 67 NA NA 68 69 70 71 72 73 74 75 76 77 78 79
我怎样才能处理列表中每一个 tibble 的所有行?
这是一种选择:在下面的代码中,我们使用逻辑测试来查找四天温度低于 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句