【问题标题】:How to replace 2nd character of a string in a column in r如何替换r中列中字符串的第二个字符
【发布时间】:2021-01-21 08:27:13
【问题描述】:

这是一个数据框的示例。

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"

【问题讨论】:

  • 您好,我注意到您到目前为止已经提出了 5 个问题,但没有接受任何一个。请考虑从每个问题中接受一个最适合您的情况的答案。每个帖子您只能接受一个答案,但可以根据需要投票。可以参考stackoverflow.com/help/someone-answers

标签: r gsub


【解决方案1】:

一种天真的方法:

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"

【讨论】:

    【解决方案2】:

    您可以这样做:

    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"
    

    【讨论】:

      【解决方案3】:

      使用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"
      

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

      【讨论】:

      • 嘿!你能解释一下这是如何工作的吗?
      • 效果很好,但我不知道它是如何工作的。你能解释一下正则表达式吗?谢谢!
      • 我为正则表达式添加了解释。
      猜你喜欢
      • 2015-10-24
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多