【问题标题】:How to remove + (plus sign) from string in R?如何从R中的字符串中删除+(加号)?
【发布时间】:2016-06-18 20:59:21
【问题描述】:

假设我使用 gsub 并想从字符串中删除以下 (=,+,-) 符号并替换为下划线。

当我尝试使用带有加号 (+) 的 gsub 时,有人可以描述发生了什么吗?

test<- "sandwich=bread-mustard+ketchup"
# [1] "sandwich=bread-mustard+ketchup"

test<-gsub("-","_",test)
# [1] "sandwich=bread_mustard+ketchup"

test<-gsub("=","_",test)
# [1] "sandwich_bread_mustard+ketchup"

test<-gsub("+","_",test)
#[1] "_s_a_n_d_w_i_c_h___b_r_e_a_d___m_u_s_t_a_r_d_+_k_e_t_c_h_u_p_"

【问题讨论】:

  • 您可以设置fixed = TRUE或转义“+”。
  • 太好了,谢谢!
  • 在我看来,R 是一个弱正则表达式平台。如果您的大部分工作都属于这种类型,那么学习 bash 正则表达式工具和/或 Perl 将是值得的。
  • gsub("[+]", "_", test)

标签: r gsub stringr


【解决方案1】:

试试

test<- "sandwich=bread-mustard+ketchup"
test<-gsub("\\+","_",test)
test
[1] "sandwich=bread-mustard_ketchup"

+ 是一个特殊字符。你需要逃避它。例如,与. 相同。如果你 google regex 或正则表达式,你会找到相应的特殊字符列表。例如,here+ 被描述为指示1 or more of previous expression。有关特殊字符、正则表达式和 R 的更多信息,请参阅 herehere

一般来说,您的上述代码可以通过以下方式更有效地编写:

 test<- "sandwich=bread-mustard+ketchup"
 test<-gsub("[-|=|\\+]","_",test)
 test
 [1] "sandwich_bread_mustard_ketchup"

这里我使用了一个基本上可以读作[either this or that or something else]的构造,其中|对应or

【讨论】:

    【解决方案2】:
    test<-gsub("+","_",test,fixed = TRUE)
    

    归功于 Jota

    【讨论】:

    • 这也比使用\\+ 而不使用fixed = TRUE 更快。
    【解决方案3】:

    我也被困住了。以下代码对我有用。

    test<- "sandwich=bread-mustard+ketchup"
    test<-gsub("\\+","_",test)
    test
    [1] "sandwich=bread-mustard_ketchup"
    

    但是,有一次它不起作用。我试过 Ian's solution 。它奏效了。

    【讨论】:

      猜你喜欢
      • 2013-07-19
      • 2016-11-08
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      相关资源
      最近更新 更多