Insert Character Pattern at Particular Position of String in R | gsub, paste | User-Defined Function

preview_player
Показать описание
R code of this video:

my_string <- "abcdefghi" # Create example string
my_string # Print example string

my_string_new1 <- gsub("^(.{5})(.*)$", # Apply gsub
"\\1_XXX_\\2",
my_string)
my_string_new1 # Print new string

fun_insert <- function(x, pos, insert) { # Create own function
gsub(paste0("^(.{", pos, "})(.*)$"),
paste0("\\1", insert, "\\2"),
x)
}

my_string_new2 <- fun_insert(x = my_string, # Apply own function
pos = 5,
insert = "_YYY_")
my_string_new2 # Print new string

Follow me on Social Media:

Рекомендации по теме
Комментарии
Автор

As always, clear and well explained. Thank you so much!

Kat-lxqq
join shbcf.ru