Chris
Chris

Reputation: 515

For loop over list of items to use in R's gsub

In R, I want to loop over items to replace in a column.

the input into the function is a list of items and I want to return the list after removing any and all items within itemsToBeRemoved list.

removePunctuation <- function(punctuationObject){
    itemsToBeRemoved <- list(".", ",", ";", ":", "'", "!", "#", "-", "--")
    objectApplyTo <- punctuationObject
    for (itemToReplace in itemsToBeRemoved){
        resultObject <- gsub("itemToReplace", "", objectApplyTo, fixed=TRUE)
        return(resultObject)   
    }
}

I expect all instances of ".", ",", ";", ":", "'", "!", "#", "-", "--" to be removed from a list of character elements.

Upvotes: 2

Views: 624

Answers (2)

user123
user123

Reputation: 175

You have several problems, one of them is that if you want to make it work in a list, you are overriding constantly the values of it. Also the pattern "." it's problematic for you. Because it takes it as the "." wildcard, not just a plain dot. Check this:

removePunctuation <- function(punctuationObject){
  itemsToBeRemoved <- list("\\.", ",", ";", ":", "'", "!", "#", "-", "--")
  for (item in itemsToBeRemoved){
    punctuationObject <- gsub(item, "", punctuationObject)
    print(punctuationObject)

  }
  return(punctuationObject)  
}

punctuationObject <- list("a,", "b", "c#")


removePunctuation(punctuationObject)

Upvotes: 1

Rui Barradas
Rui Barradas

Reputation: 76402

A base R solution could be

removePunctuation <- function(punctuationObject){
  itemsToBeRemoved <- c(".", ",", ";", ":", "'", "!", "#", "-", "--")
  resultObject <- punctuationObject
  for (itemToReplace in itemsToBeRemoved){
    resultObject <- gsub(itemToReplace, "", resultObject, fixed = TRUE)
  }
  resultObject
}

x <- c("This, that; end.", "Second: single quote' etc !")

removePunctuation(x)
#[1] "This that end"            "Second single quote etc "

Upvotes: 3

Related Questions