str_replace 到特定位置
str_replace to a particular position
我正在尝试清理来自历史数据库的关于收入的变量。我想将所有“英镑”替换为“英镑”,但将其放在数字之后。例如“每年约 500 英镑”-->“每年约 500 磅”。
我可以轻松完成第一部分:
stringr::str_replace_all("About £500 per annum" ,"£", "pounds")
[1] "About pounds500 per annum"
但我无法将它放在数字后面,这很重要,因为其他输入案例可能采用以下形式:
"大约 200 磅 0s 0d",
“124.21.0”,“124 英亩,租金 140 英镑,包括 30 英镑的租金”
有人知道优雅的方法吗?
您可以在此处使用捕获组:
library(stringr)
x <- "About £500 per annum"
str_replace_all(x, "£(\d+(?:\.\d+)?)", "\1 pounds")
[1] "About 500 pounds per annum"
我也添加了点,将 £30.00 转换为 30.00 英镑。因此,对于 gsub,我们捕获 £(将是 \1),然后是金额(\2)。替换将是数字 catch 后跟单词磅。
v <- c("About 200 pounds 0s 0d", "124.21.0", "124 acres let at £140 including a rent charge of £30.00")
gsub("(£)([0-9\.]+)", "\2 pounds", v)
# [1] "About 200 pounds 0s 0d"
# [2] "124.21.0"
# [3] "124 acres let at 140 pounds including a rent charge of 30.00 pounds"
我正在尝试清理来自历史数据库的关于收入的变量。我想将所有“英镑”替换为“英镑”,但将其放在数字之后。例如“每年约 500 英镑”-->“每年约 500 磅”。
我可以轻松完成第一部分:
stringr::str_replace_all("About £500 per annum" ,"£", "pounds")
[1] "About pounds500 per annum"
但我无法将它放在数字后面,这很重要,因为其他输入案例可能采用以下形式:
"大约 200 磅 0s 0d", “124.21.0”,“124 英亩,租金 140 英镑,包括 30 英镑的租金”
有人知道优雅的方法吗?
您可以在此处使用捕获组:
library(stringr)
x <- "About £500 per annum"
str_replace_all(x, "£(\d+(?:\.\d+)?)", "\1 pounds")
[1] "About 500 pounds per annum"
我也添加了点,将 £30.00 转换为 30.00 英镑。因此,对于 gsub,我们捕获 £(将是 \1),然后是金额(\2)。替换将是数字 catch 后跟单词磅。
v <- c("About 200 pounds 0s 0d", "124.21.0", "124 acres let at £140 including a rent charge of £30.00")
gsub("(£)([0-9\.]+)", "\2 pounds", v)
# [1] "About 200 pounds 0s 0d"
# [2] "124.21.0"
# [3] "124 acres let at 140 pounds including a rent charge of 30.00 pounds"