从r中的角色向量提取有效数字

发布于 2025-02-06 02:33:05 字数 478 浏览 1 评论 0 原文

假设我有以下字符vector

c(“ hi”,“ 4”,“ -21”,“ 6.5”,“ 7.5”,“ -2.2”,“ 4H”)

现在i想要仅提取上述向量中的有效数字:

c(“ 4”,“ -21”,“ 6.5”,“ -2.2”)

注意:两者之间的一个空间。和 7中的5。 5 因此不是有效的数字。

我正在尝试使用Regex /^ - ?(0 | [1-9] \\ d*)(\\。\\ d+)?$/ here ,但没有运气。

那么,从字符向量提取有效数字的正则是什么?

Suppose I have the below character vector

c("hi", "4", "-21", "6.5", "7. 5", "-2.2", "4h")

Now I want to extract only valid numbers which are in the above vector:

c("4", "-21", "6.5", "-2.2")

note: one space in between . and 5 in 7. 5 so not a valid number.

I was trying with regex /^-?(0|[1-9]\\d*)(\\.\\d+)?$/ which is given here but no luck.

So what would be the regex to extract valid numbers from a character vector?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫九 2025-02-13 02:33:06

我们可以使用 grep 将数字与。字符串

grep("^-?[0-9.]+$", v1, value = TRUE)
[1] "4"    "-21"  "6.5"  "-2.2"

或附带案例

grep("^[ -]?[0-9]+(\\.\\d+)?$", c(v1, "4.1.1"), value = TRUE)
[1] "4"    "-21"  "6.5"  "-2.2"

grep("^[ -]?[0-9]+(\\.\\d+)?$", c(v1, "4.1.1", " 2.9"), value = TRUE)
[1] "4"    "-21"  "6.5"  "-2.2" " 2.9"

We can use grep that matches digits with . from the start (^) till the end ($) of the string

grep("^-?[0-9.]+
quot;, v1, value = TRUE)
[1] "4"    "-21"  "6.5"  "-2.2"

Or for fringe cases

grep("^[ -]?[0-9]+(\\.\\d+)?
quot;, c(v1, "4.1.1"), value = TRUE)
[1] "4"    "-21"  "6.5"  "-2.2"

grep("^[ -]?[0-9]+(\\.\\d+)?
quot;, c(v1, "4.1.1", " 2.9"), value = TRUE)
[1] "4"    "-21"  "6.5"  "-2.2" " 2.9"
霞映澄塘 2025-02-13 02:33:05

as.numeric 已经做得很好。任何有效数字的东西都可以成功地胁迫到数字,其他所有内容都是 na

x = c("hi", "4", "-21", "6.5", "7. 5", "-2.2", "4h")
y = as.numeric(x)
y = y[!is.na(y)]
y
# [1]   4.0 -21.0   6.5  -2.2

as.numeric already does a great job of this. Anything that's a valid number can be successfully coerced to numeric, everything else is NA.

x = c("hi", "4", "-21", "6.5", "7. 5", "-2.2", "4h")
y = as.numeric(x)
y = y[!is.na(y)]
y
# [1]   4.0 -21.0   6.5  -2.2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文