题
如果我的数据包含以下元素的分类变量 "Q7", "Q2"
, 等等,我该如何替换它 "7 Queen", "2 Queen"
, , ETC。?
解决方案
对于初学者来说,如果您还包含您已经尝试过的代码,那么您将能够从提出问题中获得最大收益。那是说...
对于大型数据集来说,也许不是解决此问题的最有效方法,但这两种方法似乎在您的示例中效果很好。 example(strsplit)
有一个很好的字符串反转函数可供我们使用。
> strReverse <- function(x)
sapply(lapply(strsplit(x, NULL), rev), paste, collapse = "")
> strg <- c("Q7", "Q2")
> GS <- gsub("Q", strReverse(" Queen"), strg)
> strReverse(GS)
[1] "7 Queen" "2 Queen"
另一种方法是使用 paste
> S <- paste0(strReverse(strg), "ueen")
> gsub("Q", " Q", S)
[1] "7 Queen" "2 Queen"
其他提示
正则表达式
(Q)(\d)
替换正则表达式
$2 Queen
描述
1st Capturing group (Q)
Q matches the character Q literally (case insensitive)
2nd Capturing group (\d)
\d match a digit [0-9]
g modifier: global. All matches (don't return on first match)
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
笔记: 每封信都需要其中一个
不隶属于 StackOverflow