测试字符串中的数字元素 [英] Test for numeric elements in a character string
问题描述
我想测试一个字符串,看看哪些元素实际上可以是数字.我可以使用正则表达式来测试整数是否成功,但我想查看哪些元素具有所有数字和 1 个或更少的小数.以下是我尝试过的:
I want to test a character string and see which elements could actually be numeric. I can use regex to test for integer successful but am looking to see which elements have all digits and 1 or less decimals. Below is what I've tried:
x <- c("0.33", ".1", "3", "123", "2.3.3", "1.2r")
!grepl("[^0-9]", x) #integer test
grepl("[^0-9[\\.{0,1}]]", x) # I know it's wrong but don't know what to do
我正在寻找一个逻辑输出,所以我希望得到以下结果:
I'm looking for a logical output so I'd expect the following results:
[1] TRUE TRUE TRUE TRUE FALSE FALSE
推荐答案
也许你的数据的其他部分更复杂是有原因的,这会破坏这一点,但我的第一个想法是:
Maybe there's a reason some other pieces of your data are more complicated that would break this, but my first thought is:
> !is.na(as.numeric(x))
[1] TRUE TRUE TRUE TRUE FALSE FALSE
正如下面 Josh O'Brien 所指出的,这不会拾取诸如 7L
之类的东西,R 解释器会将其解析为整数 7.如果您需要将它们包含为合理的数字"一种方法是先用正则表达式挑选它们,
As noted below by Josh O'Brien this won't pick up things like 7L
, which the R interpreter would parse as the integer 7. If you needed to include those as "plausibly numeric" one route would be to pick them out with a regex first,
x <- c("1.2","1e4","1.2.3","5L")
> x
[1] "1.2" "1e4" "1.2.3" "5L"
> grepl("^[[:digit:]]+L",x)
[1] FALSE FALSE FALSE TRUE
...然后使用 gsub
和索引从那些元素中去掉L".
...and then strip the "L" from just those elements using gsub
and indexing.
这篇关于测试字符串中的数字元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!