Home > Enterprise >  How to remove nth character in string?
How to remove nth character in string?

Time:05-31

I there any way to drop a character by its index from the string? For instance, drop every second letter from these words:

name <- c("Jackkk","Markkk","Jayyy")

CodePudding user response:

You can use sub:

sub('(^.).(.*$)', '\\1\\2', name)
#> [1] "Jckkk" "Mrkkk" "Jyyy" 

CodePudding user response:

A non-regex, less elegant approach that is amenable to any position could be:

remove_n <- 2 #position to remove

unlist(lapply(strsplit(name, ""), function(x)
  paste(x[-remove_n], collapse = "")))

# [1] "Jckkk" "Mrkkk" "Jyyy"

# Other positions
remove_n <- 3
# [1] "Jakkk" "Makkk" "Jayy" 
remove_n <- 1
# [1] "ackkk" "arkkk" "ayyy" 

  • Related