R - count matches between characters of one string and another, no replacement

后端 未结 2 836
生来不讨喜
生来不讨喜 2020-12-31 10:42

I have a keyword (e.g. \'green\') and some text (\"I do not like them Sam I Am!\").

I\'d like to see how many of the characters in the keyword (\'g\', \'r\',

相关标签:
2条回答
  • 2020-12-31 11:10

    The function pmatch() is great for this. Though it would be instinctual to use length here, length has no na.rm option. So to work around this nuisance, sum(!is.na()) is used.

    keyword <- unlist(strsplit('greeen', ''))
    text <- unlist(strsplit('idonotlikethemsamiam', ''))
    
    sum(!is.na(pmatch(keyword, text)))
    
    # [1] 3
    
    keyword2 <- unlist(strsplit("red", ''))
    sum(!is.na(pmatch(keyword2, text)))
    
    # [1] 2
    
    0 讨论(0)
  • 2020-12-31 11:27

    Perhaps you are looking to find the UNIQUE components of your keyword? Try:

    keyword <- unique(strsplit('greeen','')[[1]])
    
    0 讨论(0)
提交回复
热议问题