我有一个长矢量。每个元素都是一个字符串。每个字符串可以拆分为由','分隔的子字符串。R如何用一个新子串替换较长字符串中的子串
我想检查我的向量中的每个字符串是否至少包含一个'bad'字符串。如果是这样,那么包含该'坏'字符串的整个SUB字符串应该替换为一个新字符串。我写了一个带循环的长函数。但我可以发誓必须有一个更简单的方法来做到这一点 - 也许用stringr? 非常感谢您的建议!
# Create an example data frame:
test <- data.frame(a = c("str1_element_1_aaa, str1_element_2",
"str2_element_1",
"str3_element_1, str3_element_2_aaa, str3_element_3"),
stringsAsFactors = F)
test
str(test)
# Defining my long function that checks if each string in a
# vector contains a substring with a "bad" string in it.
# If it does, that whole substring is replaced with a new string:
library(stringr)
mystring_replace = function(strings_vector, badstring, newstring){
with_string <- grepl(badstring, strings_vector) # what elements contain badstring?
mysplits <- str_split(string = test$a[with_string], pattern = ', ') # split those elements with badstring based on ', '
for (i in 1:length(mysplits)) { # loop through the list of splits:
allstrings <- mysplits[[i]]
for (ii in 1:length(allstrings)) { # loop through substrings
if (grepl(badstring, allstrings[ii])) mysplits[[i]][ii] <- newstring
}
}
for (i in seq_along(mysplits)) { # merge the split elements back together
mysplits[[i]] <- paste(mysplits[[i]], collapse = ", ")
}
strings_vector[with_string] <- unlist(mysplits)
return(strings_vector)
}
# Test
mystring_replace(test$a, badstring = '_aaa', newstring = "NEW")
而不是使用3 for循环,你可以分裂一个坏的字符串,并加入一个好的字符串。 – numbtongue
好主意,但这不会帮助我。我不想加入一个很好的字符串。我想用新的子字符串替换包含坏字符串的WHOLE子字符串。 – user3245256