【问题标题】:Trying to extract/count the unique characters in a string (of class character)尝试提取/计算字符串中的唯一字符(类字符)
【发布时间】:2021-12-25 01:02:39
【问题描述】:

嗨,我想做的是计算字符串中唯一字符的数量。这是我的数据框的样子

Text            unique char count
banana              3
banana12            5
Ace@343             6

大小写无关紧要,我想得到的是输出中的唯一字符(数字、字母)

我尝试了独特的、不同的功能等,但是它们为列中的整个列提供了输出,但我需要为每个对应的单元格提供输出,如上所示。

【问题讨论】:

    标签: r character unique distinct


    【解决方案1】:

    在基础 R 中你可以这样做:

    df$char_count <- sapply(strsplit(df$Text, ""), function(x) length(unique(x)))
    
    df
    #>       Text char_count
    #> 1   banana          3
    #> 2 banana12          5
    #> 3  Ace@343          6
    

    数据

    df <- data.frame(Text = c("banana", "banana12", "Ace@343"))
    

    reprex package (v2.0.0) 于 2021 年 11 月 12 日创建

    【讨论】:

    • 艾伦,泰!这么多,它工作!
    • 如果我在上面的例子中只计算特殊字符的数量为“@”,我尝试了 - df$char_count
    【解决方案2】:

    您可以直接使用regex 进行计数

    df %>%
       mutate(char_count = str_count(Text, "(.)(?!.*\\1)"))
    
          Text char_count
    1   banana          3
    2 banana12          5
    3  Ace@343          6
    

    【讨论】:

    • Ty Onyambu 但是我现在只尝试提取 spl 字符,所以在我的问题中,我只需要 "@" 作为下一列的输出 1 ,其余的应该是 0没有 spl 字符。我试过 df$char_count
    • @vicky 以上给出了问题中发布的预期结果。没有提到特殊字符。
    • @vicky 在特殊字符的情况下,这取决于您将什么定义为特殊字符,例如 df %&gt;%mutate(Text = str_count(Text, '\\W')) 适合我。 df %&gt;%mutate(Text = str_count(Text, '[[:punct:]]')) 也有效
    • 嗨,我已经用过 [[:punct:]] 因为它是 # $ % & ... 的缩写。@
    • @vicky 是的,这对我有用,即给出 0,0,1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    相关资源
    最近更新 更多