且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从R中的某个字符截断字符串

更新时间:2023-02-26 11:29:57

Joshua 的解决方案工作正常.不过,我会使用 sub 而不是 gsub .gsub 用于替换字符串中多次出现的模式 - sub 用于替换一次.模式也可以简化一点:

Joshua's solution works fine. I'd use sub instead of gsub though. gsub is for substituting multiple occurrences of a pattern in a string - sub is for one occurrence. The pattern can be simplified a bit too:

> x <- c("WDN.TO","WDR.N","WDS.AX","WEC.AX","WEC.N","WED.TO")
> sub("^[^.]*", "", x)
[1] ".TO" ".N"  ".AX" ".AX" ".N"  ".TO"

...但是如果字符串和问题中一样规则,那么简单地去除前 3 个字符就足够了:

...But if the strings are as regular as in the question, then simply stripping the first 3 characters should be enough:

> x <- c("WDN.TO","WDR.N","WDS.AX","WEC.AX","WEC.N","WED.TO")
> substring(x, 4)
[1] ".TO" ".N"  ".AX" ".AX" ".N"  ".TO"