替换子串

基本类型 / 字符串

text <- "3, 2, 1, go!"
text <- gsub("1", "one", text, fixed = TRUE)
text <- gsub("2", "two", text, fixed = TRUE)
text <- gsub("3", "three", text, fixed = TRUE)
# text = three, two, one, go!

# gsub() replaces all occurrences
ones <- "1 1 1"
all_replaced <- gsub("1", "one", ones,
                     fixed = TRUE)
# all_replaced = one one one

# sub() replaces the first one only
first_only <- sub("1", "one", ones, fixed = TRUE)
# first_only = one 1 1

cat("text =", text, "\n")
cat("all_replaced =", all_replaced, "\n")
cat("first_only =", first_only, "\n")