在R中,我想遍历要在列中替换的项目。
该函数的输入是项目列表,我想在删除itemsToBeRemoved列表中的所有项目之后返回该列表。
removePunctuation <- function(punctuationObject){
itemsToBeRemoved <- list(".", ",", ";", ":", "'", "!", "#", "-", "--")
objectApplyTo <- punctuationObject
for (itemToReplace in itemsToBeRemoved){
resultObject <- gsub("itemToReplace", "", objectApplyTo, fixed=TRUE)
return(resultObject)
}
}
我希望从列表中删除“。”,“,”,“;”,“:”,“'”,“!”,“#”,“-”,“-”的所有实例字符元素。
答案 0 :(得分:1)
基本的R解决方案可能是
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 "
答案 1 :(得分:1)
您有几个问题,其中之一是,如果您想使其在列表中起作用,那么您将不断覆盖它的值。也是模式“。”这对你来说是有问题的。因为它将它当作“。”通配符,而不仅仅是一个普通的点。 检查一下:
removePunctuation <- function(punctuationObject){
itemsToBeRemoved <- list("\\.", ",", ";", ":", "'", "!", "#", "-", "--")
for (item in itemsToBeRemoved){
punctuationObject <- gsub(item, "", punctuationObject)
print(punctuationObject)
}
return(punctuationObject)
}
punctuationObject <- list("a,", "b", "c#")
removePunctuation(punctuationObject)