Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove nth character in string?

Tags:

r

dplyr

tidyverse

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")

2 Answers

You can use sub:

sub('(^.).(.*$)', '\\1\\2', name)
#> [1] "Jckkk" "Mrkkk" "Jyyy" 
like image 73
Allan Cameron Avatar answered Dec 20 '25 05:12

Allan Cameron


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" 

like image 44
jpsmith Avatar answered Dec 20 '25 06:12

jpsmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!