替换文本向量中的字符串 无包

Replace strings in a vector of text no packages

我有 2 个向量:

Param<-c("alpha","beta","theta")
Trend<-c("b","c","ac","bc")

我想用 Param 向量中的项替换趋势向量中的每一项,“a”是第一个元素 (alpha),b 是第二个 (beta),依此类推...

期望的结果是:

Result=("beta","theta","alphatheta","betatheta")

如果可能的话我不想使用任何包,如果不是的话欢迎任何想法:)

来自 stringr 的带有 str_replace 的选项,可以采用命名向量进行替换

library(stringr)
str_replace_all(Trend, set_names(Param, letters[1:3]))
#[1] "beta"       "theta"      "alphatheta" "betatheta" 

或者如果我们不想使用任何包,请在循环中使用 gsub

lts <- letters[1:3]
for(i in seq_along(lts)) Trend <- gsub(lts[i], Param[i], Trend)
Trend