向 R 中的字符串向量添加字母

问题描述 投票:0回答:1

忽略我的

input
中的主题标记行,有没有办法添加:

  • A*
    在没有
    *
    前缀的“字母数字”元素之前,出现在
    ~
  • 之后
  • R*
    在没有
    *
    前缀的“字母数字”元素之前并出现在
    ~~
    之后?

所需的

output
如下所示。

input <- "y ~ x1 + x2
           ## Variances of x1 and x2 are 1
           x1 ~~ 1*x1
           x2 ~~ 1*x2
           ## x1 and x2 are correlated
           x1 ~~ x2"

output <- "y ~ A*x1 + A*x2
           ## Variances of x1 and x2 are 1
           x1 ~~ 1*x1
           x2 ~~ 1*x2
           ## x1 and x2 are correlated
           x1 ~~ R*x2"
r regex string stringr
1个回答
0
投票

使用“gsub”:

   # Input string
input <- "y ~ x1 + x2
           ## Variances of x1 and x2 are 1
           x1 ~~ 1*x1
           x2 ~~ 1*x2
           ## x1 and x2 are correlated
           x1 ~~ x2"

# Function to add prefixes before alphanumeric elements based on patterns
addPrefixes <- function(input) {
  # Add "A*" before alphanumeric elements that don't have a * prefix and appear after ~
  output <- gsub("(?<=~ )([^*\\s]+)", "A*\\1", input, perl = TRUE)
  
  # Add "R*" before alphanumeric elements that don't have a * prefix and appear after ~~
  output <- gsub("(?<=~~ )([^*\\s]+)", "R*\\1", output, perl = TRUE)
  
  return(output)
}

output <- addPrefixes(input)
cat(output)
© www.soinside.com 2019 - 2024. All rights reserved.