【问题标题】:Create a column with multiple categories based on string patterns in Tidyverse根据 Tidyverse 中的字符串模式创建具有多个类别的列
【发布时间】:2021-09-19 11:20:52
【问题描述】:

I checked this question,但不确定如何将其用于多个类别(不仅仅是两个)。 This is conceptually similar,但不确定它是否是字符串的好选择。

我有一个数据框

Gender          Frequency 
female            49719         
male              14835         
NA                712           
female, male      518   

此外,还有更多选项,例如 female, female, femalemale, male, female。我有几十种组合。

我想创建一个新专栏,其中只有四个类别 - malefemalebothNA。例如,如果一个挡板female 重复多次,则将其归类为female。如果它是不同性别的组合(任何长度) - 称之为both

期望的输出:

Gender          Frequency      Category
female            49719          female 
male              14835          male
NA                712            NA
female, male      518            both
male, male, male  100            male
male, male, female 100           both

我将不胜感激tidyverse 解决方案。

【问题讨论】:

    标签: r string if-statement tidyverse


    【解决方案1】:
    library(tidyverse)
    
    df %>%
      mutate(row = row_number()) %>%
      separate_rows(Gender, sep = ',\\s*') %>%
      group_by(row) %>%
      summarise(Category = if(n_distinct(Gender) > 1) 'both' else unique(Gender), 
                Gender = toString(Gender), 
                Frequency = first(Frequency)) %>%
      select(Gender, Frequency, Category)
    
    #  Gender             Frequency Category
    #  <chr>                  <int> <chr>   
    #1 female                 49719 female  
    #2 male                   14835 male    
    #3 NA                       712 NA      
    #4 female, male             518 both    
    #5 male, male, male         100 male    
    #6 male, male, female       100 both    
    

    或者

    df %>%
      mutate(Category = map_chr(str_split(Gender, ',\\s*'), 
                              ~if(n_distinct(.) > 1) 'both' else unique(.)))
    

    可以在基础R中翻译-

    df$Category <- sapply(strsplit(df$Gender, ',\\s*'), function(x) 
                       if(length(unique(x)) > 1) 'both' else unique(x))
    

    【讨论】:

    • 非常感谢,完美的解决方案。看起来我给出了错误的数据框,但我也会尝试将其应用于不同的数据框!谢谢!
    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多