【问题标题】:In R exclude character in string when shorter version exists当存在较短版本时,在 R 中排除字符串中的字符
【发布时间】:2021-01-10 13:02:49
【问题描述】:

数据只是一个玩具示例。 have 中的每个字符都有字母。如果较短的字符包含 n-1 个字母,我想排除字符。 例如,ADB 被排除在外,因为我们有 AB。 ADE 被保留是因为我们没有 AD AE 或 DE。

have <- c('A,B', 'B,C', 'A,D,B', 'A,B,E', 'A,D,E')
want <- c('A,B', 'B,C', 'A,D,E')

我知道grepl 可能有用,但我不确定如何以计算效率高的方式执行此操作。

【问题讨论】:

    标签: r regex grepl


    【解决方案1】:

    这是拆分字符串的一种方法。

    #Split the string on comma
    tmp <- strsplit(have, ',')
    #Iterate over the index of tmp
    have[!sapply(seq_along(tmp), function(x) {
      one <- tmp[[x]]
      any(sapply(tmp[-x], function(y) sum(one %in% y)) >= (length(one) - 1) & 
          lengths(tmp[-x]) < length(one))
    })]
    
    #[1] "A,B"   "B,C"   "A,D,E"
    
    • sum(one %in% y) 计算当前字符串中有多少个字符出现在另一个字符串中。

    • &gt;= (length(one) - 1) 确保 n-1 of the letters 条件。

    • lengths(tmp[-x]) &lt; length(one) 确保它更短。

    【讨论】:

      猜你喜欢
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      相关资源
      最近更新 更多