【问题标题】:R - dataframe with text, replace string at positionR - 带有文本的数据框,在位置替换字符串
【发布时间】:2020-07-29 17:03:23
【问题描述】:

如何用新字符串替换日期(或任何文本)?请不要使用正则表达式,因为文本可能始终是唯一的,但日期始终位于同一位置。

dt <-
  data.frame(
    id = c(1, 2, 3),
    text = c(
      "It was 2020-01-11",
      "It was 2020-03-21",
      "It was 2020-04-31"
    )
  )

结果应该是。我可以通过 substring 命令提取该日期。但是我怎样才能把它放到我的文本列呢?

result <-
  data.frame(
    id = c(1, 2, 3),
    text = c(
      "It was 2020-01-01",
      "It was 2020-01-01",
      "It was 2020-01-01"
    )
  )

【问题讨论】:

    标签: r substring


    【解决方案1】:
    result <- dt
    result$text <- gsub(pattern = "^It was 2020\\-[0-9]{2}\\-[0-9]{2}$", replacement = "It was 2020-01-01", result$text)
    

    或者,如果您只想将日期模式组之前的所有文本抓取到第一组中,并将看起来像日期 (2020-mm-dd) 的模式替换为固定值。

    result$text <- gsub(pattern = "^(.*) (2020\\-[0-9]{2}\\-[0-9]{2})(.*)", replacement = "\\1 2020-01-01 \\3", result$text)
    

    【讨论】:

    • 嗨 gwd,我的错,对不起。我应该写出通过正则表达式的解决方案是不可能的,因为文本可能总是唯一的。我只想用另一个字符串替换字符串中的特定位置。
    • 请定义一个您无法通过正则表达式定义/到达的特定位置?
    【解决方案2】:

    我们可以使用substring 和paste

    out <- transform(dt, text = paste0(substring(text, 1, 7), substring(text[1], 8)))
    out 
    #  id              text
    #1  1 It was 2020-01-11
    #2  2 It was 2020-01-11
    #3  3 It was 2020-01-11
    

    或者另一个选项是substr assignment

    dt$text <- as.character(dt$text)
    substr(dt$text, 8, nchar(dt$text)) <- substring(dt$text[1], 8)
    dt
    #  id              text
    #1  1 It was 2020-01-11
    #2  2 It was 2020-01-11
    #3  3 It was 2020-01-11
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      相关资源
      最近更新 更多