【问题标题】:Replacing some characters in a text column in R替换R中文本列中的一些字符
【发布时间】:2023-01-27 14:12:43
【问题描述】:

我有一个包含文本列的数据集,其中包含文本和一个以 sa 开头的术语,后面有两个 following digits。数据快照如下:

df_new <- data.frame(
  given_info=c('SA12 is given','he has his sa12',
         'she will get Sa15','why not having an sa31',
         'his SA23 is missing', 'sa12 is given'))

df_new %>% select(given_info)

              given_info
1          SA12 is given
2        he has his sa12
3      she will get Sa15
4 why not having an sa31
5    his SA23 is missing
6          sa12 is given

我需要用术语 document 替换任何带有 sa with the two digits 的术语。因此,感兴趣的结果是:

              given_info
1          document is given
2          he has his document
3          she will get document
4          why not having an document
5         his document is missing
6          document is given

非常感谢您的提前帮助!

【问题讨论】:

    标签: regex dplyr text rstudio data-cleaning


    【解决方案1】:

    我们可以在这里使用gsub(),如下所示:

    df_new$given_info <- gsub("\b[sS][aA]\d{2}\b", "document", df_new$given_info)
    df_new
    
                      given_info
    1          document is given
    2        he has his document
    3      she will get document
    4 why not having an document
    5    his document is missing
    6          document is given
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      相关资源
      最近更新 更多