【问题标题】:Remove Backslash and Quotations in R删除 R 中的反斜杠和引号
【发布时间】:2016-03-24 02:57:13
【问题描述】:

如何从 R 中的以下字符串中删除引号?

test = "\"LAST4\""
noquote(test)
[1] "LAST4"

我正在手动读取数据,无法删除引号和反斜杠。

【问题讨论】:

  • “我正在手动读取数据”是什么意思?最好在导入时解决问题,而不是稍后解决。

标签: r string quotes backslash


【解决方案1】:

“R - gsub 替换反斜杠”中的解决方案对我有用。

例子:

library(stringr)
df$variable <- str_replace(df$variable,"\\\\\\\","")

df$variable before: "xyz\"
df$variable after:"xyz"

【讨论】:

    【解决方案2】:

    试试:

    gsub("\\\"","",test)
    #[1] "LAST4"
    

    修改

    @Roland 的解决方案提高了可读性和性能:

    require(rbenchmark)
    test = "\"LAST4\""
    
    a <- function() gsub("\\\"","",test)
    b <- function() gsub('\"', "", test, fixed = TRUE)
    
    benchmark(a(), b(), replications=10^7)
    #  test replications elapsed relative user.self sys.self user.child sys.child
    #1  a()     10000000  87.216    1.801    87.914        0          0         0
    #2  b()     10000000  48.430    1.000    46.989        0          0         0
    

    【讨论】:

    • 尝试实际对函数评估进行基准测试:benchmark(a(), b(), replications=10^5)
    • 哦,确实,我是多么愚蠢……谢谢@Roland!我将修改我的编辑。
    【解决方案3】:

    如果不使用正则表达式,则无需转义:

    gsub('\"', "", test, fixed = TRUE)
    #[1] "LAST4"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 2021-10-23
      • 2018-07-26
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多