我有一个数据框 df1。我想在每一列找到最小转折点,最小点前后的值都比它大。例如在x=c(2,5,3,6,1,1,1)中,我想确定最小转折点在3,但是用min函数,我只能找到最小值点是 1。如果没有最小点,我想得到 NA。谢谢。
> df
structure(list(x = c(2, 5, 3, 6, 1, 1, 1), y = c(6, 9, 3, 6,
3, 1, 1), z = c(9, 3, 5, 1, 4, 6, 2)), row.names = c(NA, -7L), class = c("tbl_df",
"tbl", "data.frame"))
df1>
x y z
2 6 9
5 9 3
3 3 5
6 6 1
1 3 4
1 1 6
1 1 2
期望的结果如下所示。
df2>
x y z
3 3 1
最佳答案
您可以使用 lead
和 lag
将当前值与上一个和下一个值进行比较。
library(dplyr)
df %>% summarise(across(.fns = ~min(.x[which(lag(.x) > .x & lead(.x) > .x)])))
# x y z
# <dbl> <dbl> <dbl>
#1 3 3 1
关于r - 在数据框中查找最小转折点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65337784/