gpt4 book ai didi

r - 在 dplyr mutate 中查找 cummax 的索引?

转载 作者:行者123 更新时间:2023-12-04 06:58:43 25 4
gpt4 key购买 nike

我有以下代码:

library(dplyr)
set.seed(10)
test<-data.frame(x=runif(10,0,1),y=rep(c(1,2),5))
test <- test %>%
group_by(y) %>%
mutate(max_then=cummax(x))

test

哪个输出
Source: local data frame [10 x 3]
Groups: y

x y max_then
1 0.50747820 1 0.5074782
2 0.30676851 2 0.3067685
3 0.42690767 1 0.5074782
4 0.69310208 2 0.6931021
5 0.08513597 1 0.5074782
6 0.22543662 2 0.6931021
7 0.27453052 1 0.5074782
8 0.27230507 2 0.6931021
9 0.61582931 1 0.6158293
10 0.42967153 2 0.6931021

我想添加另一个变异列,它将添加从中计算 max_then 的行号/索引。我想它会像下面这样。但我真的无法让它工作。
test %>%
group_by(y) %>%
mutate(max_then-cummax(x),
max_index=which(.$x==max_then))

预期输出为:
            x y  max_then max_index
1 0.50747820 1 0.5074782 1
2 0.30676851 2 0.3067685 2
3 0.42690767 1 0.5074782 1
4 0.69310208 2 0.6931021 4
5 0.08513597 1 0.5074782 1
6 0.22543662 2 0.6931021 4
7 0.27453052 1 0.5074782 1
8 0.27230507 2 0.6931021 4
9 0.61582931 1 0.6158293 9
10 0.42967153 2 0.6931021 4

有什么建议?我只是想知道是否可以在 mutate() 语句中执行此操作。我可以在 mutate() 语句之外进行。

最佳答案

我只会匹配 x 中的唯一实例

test %>%
mutate(max_index = match(max_then, unique(test$x)))
# Source: local data frame [10 x 4]
# Groups: y
#
# x y max_then max_index
# 1 0.50747820 1 0.5074782 1
# 2 0.30676851 2 0.3067685 2
# 3 0.42690767 1 0.5074782 1
# 4 0.69310208 2 0.6931021 4
# 5 0.08513597 1 0.5074782 1
# 6 0.22543662 2 0.6931021 4
# 7 0.27453052 1 0.5074782 1
# 8 0.27230507 2 0.6931021 4
# 9 0.61582931 1 0.6158293 9
# 10 0.42967153 2 0.6931021 4

关于r - 在 dplyr mutate 中查找 cummax 的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31525995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com