R-带文本的数据框,替换位置处的字符串

R-带文本的数据框,替换位置处的字符串,r,substring,R,Substring,如何用新字符串替换日期(或任何文本)?请不要使用regexp,因为文本可能总是唯一的,但日期总是在同一位置 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" ) ) dtresultresult我们可以使用substring和paste out <- t

如何用新字符串替换日期(或任何文本)?请不要使用regexp,因为文本可能总是唯一的,但日期总是在同一位置

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"
    )
  )

dt
result
result我们可以使用
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

我们可以将
子字符串
粘贴

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

嗨,格温,我的错,对不起。我应该指出,通过regexp解决方案是不可能的,因为文本可能总是唯一的。我只想用另一个字符串替换我字符串中的特定位置。请定义一个你无法通过正则表达式定义/到达的特殊位置?嗨,gwd,我的错,对不起。我应该指出,通过regexp解决方案是不可能的,因为文本可能总是唯一的。我只想用另一个字符串替换字符串中的特定位置。请定义一个无法通过正则表达式定义/到达的特殊位置?
result$text <- gsub(pattern = "^(.*) (2020\\-[0-9]{2}\\-[0-9]{2})(.*)", replacement = "\\1 2020-01-01 \\3", result$text)
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
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