【问题标题】:how to manipulate further the list created from group_map() in R dplyr如何进一步操作从 R dplyr 中的 group_map() 创建的列表
【发布时间】:2020-02-27 07:33:38
【问题描述】:

我对 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*))

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

【问题讨论】:

    标签: r list group-by dplyr


    【解决方案1】:

    你可以这样做:

    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())
    

    【讨论】:

    • 如果我们坚持使用group_map,输出列表如何使用?我坚持这个问题的原因是我对从组中分解子列表感到困惑......这有意义吗?
    • @mand3rd 抱歉,为什么要在这里专门使用group_map?我认为使用group_bymutate 可以直接实现您想要的。
    • 是的,我同意这个特殊的解决方案很简单。在我的原始数据中,我使用了一个函数来提取一些创建列表的值(局部最大值是特定的)。我想我过度简化了我的例子......
    • @mand3rd 更新了答案以使其适用于group_map,不确定是否有帮助。
    猜你喜欢
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    相关资源
    最近更新 更多