忽略我的
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"
使用“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)