【问题标题】:R Make identical two strings that look the same but are not identicalR 生成两个看起来相同但不相同的相同字符串
【发布时间】:2016-05-22 05:33:20
【问题描述】:

我有两个看起来相同但不相同的字符串。

> t
[1] "2009_Manaus_Aerotáxi_crash"
> t2
[1] "2009_Manaus_Aerotáxi_crash"
> identical(t,t2)
[1] FALSE
> str(t)
 chr "2009_Manaus_Aerotaxi_crash""| __truncated__
> str(t2)
 chr "2009_Manaus_Aerotáxi_crash"

如何强制这两个字符串相等?

谢谢

【问题讨论】:

  • 它们都是字符串吗?检查str()
  • 这似乎是一个数据类型问题。你能提供给我们dput(list(t=t,t2=t2))的输出吗?
  • > dput(list(t=t,t2=t2)) 结构(list(t = "2009_Manaus_Aerotáxi_crash", t2 = "2009_Manaus_Aerotáxi_crash"), .Names = c("t", "t2 "))
  • charToRaw(t) [1] 32 30 30 39 5f 4d 61 6e 61 75 73 5f 41 65 72 6f 74 61 cc 81 78 69 5f 63 72 [26] 61 73 68 charToRaw(t2) [1] 32 30 30 39 5f 4d 61 6e 61 75 73 5f 41 65 72 6f 74 c3 a1 78 69 5f 63 72 61 [26] 73 68
  • stackoverflow.com/questions/23699271/…,特别是`stri_trans_general(x, "Latin-ASCII")

标签: r string comparison


【解决方案1】:

考虑使用 stringi (https://cran.r-project.org/web/packages/stringi/) 包中的 stri_compare 方法。 如果两个字符串相等或规范等效,则返回 0。查看文档here

在你的情况下,你会这样测试它:

require('stringi')

t  = "2009_Manaus_Aerotáxi_crash"
t2 = "2009_Manaus_Aerotáxi_crash"
t3 = "1111_Manaus_Aerotáxi_crash"

ifelse( (stri_compare(t,t2) == 0), "Strings are equal", "Strings are different") 
ifelse( (stri_compare(t,t3) == 0), "Strings are equal", "Strings are different")

希望对你有帮助

【讨论】:

  • 非常感谢 selyunin,问题是我想将其中一个字符串转换为另一个字符串的“相同”等价物。也就是说,改变 t 使其变为 t2 相同。我需要它,因为我有几个这样的字符串没有合并,因为它们不相同
【解决方案2】:

如果您将数据写入 csv,然后在 Notepad++ 等程序中打开文件,然后打开查看>所有字符,您将能够查看字符串末尾是否有 LF 或 \r或\n。然后,您将更好地了解您需要删除的内容,并可以使用上述建议 (stringi::str_cmp()) 来测试您知道无法确保已修复它的字符串示例。对我来说,问题原来是空格,这解决了我的问题:

own_dept_expect %>% mutate(check_field = stringr::str_replace_all(check_field,"[:space:]","")) %>% write_csv("C:/Users/me/Desktop/spaces_suck.csv")

我在 Notepad++ 中验证了它现在都是统一的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多