gpt4 book ai didi

r - 如何进一步操作从 R dplyr 中的 group_map() 创建的列表

转载 作者:行者123 更新时间:2023-12-05 07:12:20 26 4
gpt4 key购买 nike

我是 R 的新手,我使用老式的 for 循环。我试图通过使用 dplyr 来更快地处理我的数据来更有效地编码,但我曾经对列表感到困惑。我在下面有一个简单的数据集:

df <- data_frame(group = sort(rep(1:3, 20)), 
values = signif(runif(60), 2),
thresh = ifelse(values > 0.6, TRUE, FALSE))

df %>% group_by(group) %>% group_map(~which(.$thresh == TRUE))

根据上面 group_map() 的输出,我如何,1.) 创建一个新列,其中仅包含 thresh == TRUE 的行名称,其余的是 NA,并且 2.) 创建另一列,其中包含来自 thresh 的 TRUE 值中的最大值。为了说明,我希望我的最终数据框有点像这样:

   group values  thresh idex  max
1 1 0.77 TRUE 1 NA
2 1 0.32 FALSE NA NA
3 1 0.06 FALSE NA NA
4 1 0.33 FALSE NA NA
5 1 0.51 FALSE NA NA
6 1 0.053 FALSE NA NA
7 1 0.92 TRUE 7 0.92
8 1 0.44 FALSE NA NA
...
...

我考虑过编写代码,但我在 group_map 之后卡住了:

dff %>% group_by(group) %>% 
group_map(~which(.$thresh == TRUE)) %>%
mutate(idex = *row_names_in_the_column_blank_are_NA*,
max = max(*values_from_the_indices*))

最好的方法是什么?谢谢!

最佳答案

你可以这样做:

library(dplyr)

df %>%
#For each group
group_by(group) %>%
#Give row number to TRUE thresh values and NA to FALSE thresh values
mutate(idex = replace(row_number(), !thresh, NA),
#Get maximum of values where thresh == TRUE
max_v = max(values[thresh],na.rm = TRUE),
#Replace values to NA where the value is not maximum.
max_v = replace(max_v, max_v != values, NA))

这里有一种方法可以让它与 group_map 一起工作

df %>%
bind_cols(df %>% group_by(group) %>% group_map(~{
tibble(idex = replace(seq_along(.x$thresh), !.$thresh, NA),
max_v1 = max(.x$values[.x$thresh],na.rm = TRUE),
max_v = replace(max_v1, max_v1 != .x$values, NA)) %>%
select(-max_v1)
}) %>%
bind_rows())

关于r - 如何进一步操作从 R dplyr 中的 group_map() 创建的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60428288/

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