【问题标题】:Conditioned filtering in RR中的条件过滤
【发布时间】:2020-11-20 22:25:43
【问题描述】:

我正在尝试为我编写一个自动过滤过程的函数。考虑这个专注于数据数据框的示例:

#generate mock dataframe
set.seed(1)

number <-c("4","5","6")

##groups
colors <- c("red","orange","green")
fruit <- c("apple","tomato","banana")
animal <- c("chicken","pork","cow")


vector_colors <-map(colors, ~ str_c(.,number, sep = "_"))  %>%  reduce(c)
vector_fruit <-map(fruit, ~ str_c(.,number, sep = "_"))  %>%  reduce(c)
vector_animal <-map(animal, ~ str_c(.,number, sep = "_"))  %>%  reduce(c)


vector <- c(vector_colors,vector_fruit,vector_animal)
#dataframe I'll be working with
data <-  tibble(name = vector,
                rank = runif(27, 1, 99))

我想要一个函数或 tidyverse/base R 工作流程,每组打印一个项目(即颜色、水果和动物),以便打印的项目与其组中的所有其他项目相比排名最低。在那个种子示例中,想要的结果将是以下向量:

wanted_result <-c("orange_5","apple_6","cow_6")

【问题讨论】:

    标签: r conditional-statements filtering tidyverse


    【解决方案1】:

    制作类型查找表,提取前缀,加入类型,并按类型分组以提取具有最小等级的名称:

    library(dplyr)
    type_lookup = tibble(
      prefix = c(colors, fruit, animal),
      type = rep(c("color", "fruit", "animal"), times = c(length(colors), length(fruit), length(animal)))
    )
    
    data %>%
      mutate(prefix = str_extract(name, pattern = ".*(?=_)")) %>%
      left_join(type_lookup, by = "prefix") %>%
      group_by(type) %>%
      slice_min(rank) %>%
      pull(name)
    # [1] "cow_6"    "orange_5" "apple_4" 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 2022-09-29
      相关资源
      最近更新 更多