我正在用 R 重写我的 vb.net 代码并且遇到了障碍。vb.net 中的代码本质上是计算字符串中未出现在允许字符的字符串中的字符数。vb.net 中的代码是:
StringtoConvert="ABC"
strAllowedChars="AC"
For i= 1 to len(StringtoConvert)
If InStr(1, strAllowedChars, StringtoConvert(i))=0 then
disallowed=disallowed+1
Else
End If
Next
我可以看到如何在 R 中使用循环来搜索字符串中每个允许的字符,但是在 R 中有没有办法使用像上面的 strAllowedChars 这样的聚合来做到这一点?
R 中 stringr 包的 str_count 函数是我发现的最接近的,但它看起来与整个 strAllowedChars 匹配,而不是独立查看每个字符。如何测试 StringtoConvert 以确保它仅包含 strAllowedChars 作为单个字符。换句话说,在上面的示例中,如果 StringtoConvert 中的字符与 strAllowedCharacters 中的字符之一不匹配,那么我需要将其标识为这样并使用另一个调用来替换它或直接替换它。
我尝试过的 R 代码是:
library(stringr)
testerstring<-"CYA"
testpattern<-"CA"
newtesterstring<-str_count(testerstring,testpattern)
print(newtesterstring)
所需的输出是 StringtoConvert 中基于允许的字符 strAllowedChars 被禁止的字符数。然后,我将在循环中使用它,使用 if then 语句将任何不允许的字符更改为“G”,因此如果我可以跳过计数步骤,而只是用“G”替换任何不允许的字符,那也是可取的。