Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Available function for deletion of character from certain positions of a string

Tags:

r

I am looking for a function which performs delete operation on a string based on the position.

For example, given string is like that

string1 <- "hello stackoverflow"

Suppose, I want to delete 4th,10th and 18th positions.

Preferred Output

"helo stakoverflw"

I am not sure about the existence of such function.

like image 221
user2100721 Avatar asked Oct 19 '22 07:10

user2100721


1 Answers

This worked for me.

string1 <- "hello stackoverflow"
paste((strsplit(string1, "")[[1]])[-c(4,10,18)],collapse="")
[1] "helo stakoverflw"

I used strsplit to split the string into a vector of characters, and then pasted only the desired characters back together into a string.

You could also write a function that does this:

delChar <- function(x,eliminate){
  paste((strsplit(x,"")[[1]])[-eliminate],collapse = "")
}

delChar(string1,c(4,10,18))
[1] "helo stakoverflw"
like image 121
Chase Grimm Avatar answered Oct 21 '22 05:10

Chase Grimm