我正在尝试使用包stringr
从R中的字符串中提取数字。有时,数字不存在。以下是一些示例字符串:
str <- c(
"cash dividends per share $ - $ - $ - $ 0.08 $ 0.16 cash",
"cash dividends per share $ 0.01 $ 12.10 $ 0.01 $ 0.08 $ 0.16 hello",
"cash dividends per share $ - $ - $ 0.91 $ - $ 0.16 world",
"cash dividends per share - - 0.12 - 0.16 hsac",
"cash dividends per share $ - $ - $ - $ - $ 0.16 afterwards",
"cash dividends per share $0.12 $ - $0.1 $ - $ - comes",
"cash dividends per share 0.12 - 0.12 - - text",
"cash dividends per share... 0.12 - 0.12 - - random",
"cash dividends per share...0.123 0.321 - - 0.12 blu",
"cash dividends per share ..... $ 0.12 $ - $ 0.12 $ - $ - foo",
"cash dividends per share ..... $0.42 $0.42 $- $- $- bar")
我构建了以下正则表达式,IMO应该匹配所有情况,但它没有。当然,我也尝试了各种不同的,但我无法找到正确的一个(我甚至无法看到我提出的问题):
library("stringr")
rgxp <- "cash dividends [declared]* per share[ \\.]+[\\$]?[ ]?([-0.9\\.]+)[ ]?[\\$]?[ ]?([-0.9\\.]+)[ ]?[\\$]?[ ]?([-0.9\\.]+)[ ]?[\\$]?[ ]?([-0.9\\.]+)[ ]?[\\$]?[ ]?([-0.9\\.]+).*"
str_match_all(str, rgxp)
您是否看到上述正则表达式失败的原因?
编辑:我应该说我想要的输出是 alyways 一个包含五个元素的向量,即如果没有数字,则为数字或连字符。谢谢!
答案 0 :(得分:3)
使用gsub
用空格替换任意两个或多个连续点以及任何不是减号,数字或点的字符,然后使用read.table
读入。如果希望减号出现在NA所在的位置,请忽略na.strings = "-"
。没有包使用。
DF <- read.table(text = gsub("[^-0-9.]+|\\.{2,}", " ", str), fill = TRUE, na.strings = "-")
给出这个data.frame:
> DF
V1 V2 V3 V4 V5
1 NA NA NA 0.08 0.16
2 0.010 12.100 0.01 0.08 0.16
3 NA NA 0.91 NA 0.16
4 NA NA 0.12 NA 0.16
5 NA NA NA NA 0.16
6 0.120 NA 0.10 NA NA
7 0.120 NA 0.12 NA NA
8 0.120 NA 0.12 NA NA
9 0.123 0.321 NA NA 0.12
10 0.120 NA 0.12 NA NA
11 0.420 0.420 NA NA NA
注意:如果您想用零替换NA,请使用:DF[is.na(DF)] <- 0
。
答案 1 :(得分:2)
如果你想捕捉数字和连字符:
rgxp <- "([0-9]+\\.?[0-9]*)|(-)"
str_extract_all(str, rgxp)
[[1]]
[1] "-" "-" "-" "0.08" "0.16"
[[2]]
[1] "0.01" "12.10" "0.01" "0.08" "0.16"
[[3]]
[1] "-" "-" "0.91" "-" "0.16"
[[4]]
[1] "-" "-" "0.12" "-" "0.16"
[[5]]
[1] "-" "-" "-" "-" "0.16"
[[6]]
[1] "0.12" "-" "0.1" "-" "-"
[[7]]
[1] "0.12" "-" "0.12" "-" "-"
[[8]]
[1] "0.12" "-" "0.12" "-" "-"
[[9]]
[1] "0.123" "0.321" "-" "-" "0.12"
[[10]]
[1] "0.12" "-" "0.12" "-" "-"
[[11]]
[1] "0.42" "0.42" "-" "-" "-"
如果您只想要数字:
rgxp <- "[0-9]+\\.?[0-9]*"
str_extract_all(str, rgxp)
[[1]]
[1] "0.08" "0.16"
[[2]]
[1] "0.01" "12.10" "0.01" "0.08" "0.16"
[[3]]
[1] "0.91" "0.16"
[[4]]
[1] "0.12" "0.16"
[[5]]
[1] "0.16"
[[6]]
[1] "0.12" "0.1"
[[7]]
[1] "0.12" "0.12"
[[8]]
[1] "0.12" "0.12"
[[9]]
[1] "0.123" "0.321" "0.12"
[[10]]
[1] "0.12" "0.12"
[[11]]
[1] "0.42" "0.42"