如何替换r中列中字符串的第二个字符

How to replace 2nd character of a string in a column in r

这是一个数据框的例子。

Type <- c('[C>A]','[C>G]','[C>T]')
Subtype <- c('ACA','ACT','ACC')
df <- cbind(Type, Subtype)
df
     Type    Subtype
[1,] "[C>A]" "ACA"
[2,] "[C>G]" "ACT"
[3,] "[C>T]" "ACC"

这就是我希望输出的样子

      Type    Subtype
[1,] "[C>A]" "A[C>A]A"
[2,] "[C>G]" "A[C>G]T"
[3,] "[C>T]" "A[C>T]C"

使用 stringrstr_replace :

df[, 2] <- stringr::str_replace(df[, 2], '(?<=.).', df[, 1])
df
#       Type    Subtype  
#[1,] "[C>A]" "A[C>A]A"
#[2,] "[C>G]" "A[C>G]T"
#[3,] "[C>T]" "A[C>T]C"

(?<=) 是正后视正则表达式,用于匹配未捕获的第一个字符,第二个点表示捕获并替换的第二个字符。

您可以执行以下操作:

library(stringr)
df[,2] <- str_replace(df[,2],str_split(df[,2],"",simplify = T)[,2],df[,1])

> df
     Type    Subtype  
[1,] "[C>A]" "A[C>A]A"
[2,] "[C>G]" "A[C>G]T"
[3,] "[C>T]" "A[C>T]C"

一种天真的方法:

df[, 2] <- paste0(substr(df[, 2], 1, 1), df[, 1], substr(df[, 2], 3, 3))
df
#       Type    Subtype  
# [1,] "[C>A]" "A[C>A]A"
# [2,] "[C>G]" "A[C>G]T"
# [3,] "[C>T]" "A[C>T]C"