【问题标题】:How to remove square parentheses and text within from strings in R如何从R中的字符串中删除方括号和文本
【发布时间】:2019-12-09 05:58:51
【问题描述】:

我在用 R 语言处理数据框 (test_dataframe) 列 (test_column) 值时遇到问题,如下所示:
列中的原始字符串:

test_column
6.77[9]
5.92[10]
2.98[103]

我需要去掉方括号和方括号内的任何字符,所以目标值如下:

test_column
6.77
5.92
2.98

我尝试使用 R 语言中的gsub 函数,但解决它不是很幸运,有人可以帮忙弄清楚吗?

【问题讨论】:

    标签: r regex string gsub


    【解决方案1】:

    我会使用:

    input <- c("6.77[9]", "5.92[10]", "2.98[103]")
    gsub("\\[.*?\\]", "", input)
    
    [1] "6.77" "5.92" "2.98"
    

    正则表达式模式\[.*?\] 应该匹配任何在方括号中引用的术语,并且使用gsub 会告诉R 替换所有这些术语。

    【讨论】:

    • 哇,感谢您的快速帮助,这种模式非常完美,在方括号内显示任何字符的.*? 是我之前无法找到的部分,再次感谢!
    【解决方案2】:

    您可以使用sub 并删除方括号后的所有内容。

    df$test_column <- sub("\\[.*", "", df$test_column)
    df
    #  test_column
    #1        6.77
    #2        5.92
    #3        2.98
    

    您可能希望将sub 的输出包装在as.numeric 中。


    如果前面总是有一个数值,如示例所示,您也可以使用parse_number

    readr::parse_number(df$test_column)
    #[1] 6.77 5.92 2.98
    

    数据

    df <- structure(list(test_column = c("6.77[9]", "5.92[10]", "2.98[103]"
    )), row.names = c(NA, -3L), class = "data.frame")
    

    【讨论】:

    • 是的,谢谢Shah,我也试过你的解决方案,你的想法也很完美,尤其是转换为数字的细节,感谢您的快速帮助!
    【解决方案3】:

    我们可以从stringr使用str_remove

    library(stringr)
    library(dplyr)
    df %>%
       mutate(test_column = str_remove(test_column, "\\[.*"))
    #  test_column
    #1        6.77
    #2        5.92
    #3        2.98
    

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2021-01-29
      • 2013-01-04
      • 2018-08-16
      相关资源
      最近更新 更多