tidyverse:替换字符串中的特殊字符
tidyverse: replacing special characters in string
我想用 \_
替换字符串中的 _
。
Test <-
c(".model", "sigma2", "log_lik", "AIC", "AICc", "BIC", "ar_roots",
"ma_roots")
library(stringr)
Test %>%
str_replace_all(string = ., pattern = "_", replacement = "\_")
Error: '\_' is an unrecognized escape in character string starting ""\_"
有什么提示吗?
你可以使用-
stringr::str_replace_all(Test, pattern = "_", replacement = "\\_")
#[1] ".model" "sigma2" "log\_lik" "AIC" "AICc" "BIC"
#[7] "ar\_roots" "ma\_roots"
打印时 \
被另一个 \
转义,因此您会看到两个反斜杠。要查看实际字符串,请使用 cat
cat(stringr::str_replace_all(Test, pattern = "_", replacement = "\\_"))
#.model sigma2 log\_lik AIC AICc BIC ar\_roots ma\_roots
或者用 gsub
-
gsub("_", "\\_", Test)
我想用 \_
替换字符串中的 _
。
Test <-
c(".model", "sigma2", "log_lik", "AIC", "AICc", "BIC", "ar_roots",
"ma_roots")
library(stringr)
Test %>%
str_replace_all(string = ., pattern = "_", replacement = "\_")
Error: '\_' is an unrecognized escape in character string starting ""\_"
有什么提示吗?
你可以使用-
stringr::str_replace_all(Test, pattern = "_", replacement = "\\_")
#[1] ".model" "sigma2" "log\_lik" "AIC" "AICc" "BIC"
#[7] "ar\_roots" "ma\_roots"
打印时 \
被另一个 \
转义,因此您会看到两个反斜杠。要查看实际字符串,请使用 cat
cat(stringr::str_replace_all(Test, pattern = "_", replacement = "\\_"))
#.model sigma2 log\_lik AIC AICc BIC ar\_roots ma\_roots
或者用 gsub
-
gsub("_", "\\_", Test)