【问题标题】:Find maximum value in list-column that is less or equal to value of another column in R在列表列中查找最大值小于或等于 R 中另一列的值
【发布时间】:2020-07-13 20:30:20
【问题描述】:

我有下表:

tbl1 <- tibble::tribble(
~numberEvent, ~numberNovo,
"497",        "497",
"498",        "498",
"499",        "499",
"500",        "500",
"501",        "498, 506",
"502",        "502",
"503",        "503",
"504",        "504",
"505",        "505",
"506",        "506",
"507",        "498, 506")

我正在尝试创建一个新列,其中列 numberNovo 的最大值小于或等于列 numberEvent 的值。因此,在第 5 行中,我希望得到 498 作为结果,因为它是小于 501 的最大值。在最后一行中,所需的结果将是 506。

我试图将列 numberNovo 转换为列表列,但我不知道如何从那里开始。 任何帮助表示赞赏。

提前致谢!

【问题讨论】:

    标签: r tidyverse purrr


    【解决方案1】:

    我们可以使用separate_rows来拆分列,然后通过获取'numberEvent'和'numberNovo'之间的差异进行分组,找到max差异的索引来子集'numberNovo'并将其绑定原始数据

    library(dplyr)
    library(tidyr)
    tbl1 %>%
        separate_rows(numberNovo, convert = TRUE) %>% 
        group_by(grp = numberEvent) %>%
        summarise(maxNovo = numberNovo[which.max(as.integer(numberEvent) - 
                 numberNovo)])   %>%  
        select(maxNovo) %>% 
        bind_cols(tbl1, .)
    # A tibble: 11 x 3
    #   numberEvent numberNovo maxNovo
    #   <chr>       <chr>        <int>
    # 1 497         497            497
    # 2 498         498            498
    # 3 499         499            499
    # 4 500         500            500
    # 5 501         498, 506       498
    # 6 502         502            502
    # 7 503         503            503
    # 8 504         504            504
    # 9 505         505            505
    #10 506         506            506
    #11 507         498, 506       498
    

    【讨论】:

    • 有什么方法可以让它小于或等于 numberEvent 中的值?
    • 这行得通!您使用 summarise 而不是 mutate 是有原因的吗?
    • @RamiroBentes 是的,当您使用separate_rows 拆分行时,会有更多行,summarise 可以在分组后返回单行,而 mutate 在分组后返回相同数量的行separate_rows。因此,使用了summarise
    【解决方案2】:

    我想出了一种使用 purrr 的不同方式,对于任何感兴趣的人:

    tbl1 %>% 
         mutate(maxNovo = str_split(numberNovo, ", "),
                maxNovo = map(maxNovo , ~as.numeric(.)),
                maxNovo = map2_dbl(maxNovo , numberEvent, ~ max(.x[.x <= .y]))) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 2021-07-25
      相关资源
      最近更新 更多