【问题标题】:How to append text to a column based on conditions?如何根据条件将文本附加到列?
【发布时间】:2021-12-21 13:09:02
【问题描述】:

我有一个空列指定用于对我的数据框中的条目进行分类。类别不是排他性的,即一个条目可以有多个类别。

         animals categories
1         monkey      
2 humpback whale      
3    river trout      
4        seagull      

categories 列应具有基于动物属性的类别。我知道基于向量的属性。向量中的元素不一定是完美匹配的。

mammals <- c("whale", "monkey", "dog")
swimming <- c("whale", "trout", "dolphin")

如何获得以下结果,最好不要循环?

         animals      categories
1         monkey          mammal     
2 humpback whale mammal,swimming     
3    river trout        swimming     
4        seagull      

【问题讨论】:

    标签: r dataframe conditional-statements


    【解决方案1】:

    使用stack + aggregate + grepl 的基本 R 选项

    lut <- aggregate(
      . ~ values,
      type.convert(
        stack(list(mammals = mammals, swimming = swimming)),
        as.is = TRUE
      ),
      toString
    )
    p <- sapply(
      lut$values,
      grepl,
      x = df$animals
    )
    df$categories <- lut$ind[replace(rowSums(p * col(p)), rowSums(p) == 0, NA)]
    

    给了

    > df
             animals        categories
    1         monkey           mammals
    2 humpback whale mammals, swimming
    3    river trout          swimming
    4        seagull              <NA>
    

    数据

    df <- data.frame(animals = c("monkey", "humpback whale", "river trout", "seagull"))
    

    【讨论】:

    • 我设法让它与另一个答案一起工作,但非常感谢您的回复!
    【解决方案2】:

    这可以在创建 key/val 数据集后使用 fuzzyjoin 完成 - 从 dplyr 返回命名为 listlst,将其转换为带有 enframeunnest 的两列数据集list 列,按“动物”分组,paste“类别”到单个字符串,然后与原始数据集进行连接 (regex_left_join)

    library(fuzzyjoin)
    library(dplyr)
    library(tidyr)
    library(tibble)
    keydat <- lst(mammals, swimming) %>%
         enframe(name = 'categories', value = 'animals') %>% 
         unnest(animals) %>%
         group_by(animals) %>% 
         summarise(categories = toString(categories))
    regex_left_join(df1, keydat, by= 'animals', ignore_case = TRUE) %>% 
         transmute(animals = animals.x, categories)
    # A tibble: 4 × 2
      animals        categories       
      <chr>          <chr>            
    1 monkey         mammals          
    2 humpback whale mammals, swimming
    3 river trout    swimming         
    4 seagull        <NA>       
    

    数据

    df1 <- tibble(animals = c('monkey', 'humpback whale', 'river trout', 'seagull'))
    

    【讨论】:

    • 太棒了,谢谢!有什么办法可以不区分大小写吗?
    • @szgfi 在regex_left_join 中添加ignore_case(更新后的帖子)
    • 很棒的regex_left_join 方法!
    • 感谢一百万!它有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 2021-11-23
    • 1970-01-01
    • 2019-08-04
    • 2016-11-19
    • 2018-09-25
    • 2022-01-27
    相关资源
    最近更新 更多