想知道是否有人可以帮我解决这个问题.我在下面有这些数据.
[1] "Compared with 3 months earlier . . . . . . . . 123 (100.0) 11 (8 .9 60 (48. 8) 48 (39.0) 4 (3.3) . . . . . . . . . . . . . ."
[2] "Compared with 3 months earlier . . . . . . . . 124 ( 100.0) 18 (14. 5) 60 (48.4) 42 (33 .9) 4 (3. 2) . . . . . . . . . . . . . ."
[3] "Compared with 3 months earlier . . . . . . . . 124 (100.0) 7 (5.6) 42 (33.9) 64 (51.6) 11 (8.9) . . . . . . . . . . . . . ."
Run Code Online (Sandbox Code Playgroud)
想提取上面的内容是这样的
123 100.0 11 8.9 60 48.8 48 39.0 4 3.3
124 100.0 18 14.5 60 48.4 42 33.9 4 3.2
124 100.0 7 5.6 42 33.9 64 51.6 11 8.9
Run Code Online (Sandbox Code Playgroud)
在数字和小数之间有一些随机空格应该被视为一个单独的数字.我试过用,str_extract_all()
但它没有给我预期的结果.
在正则表达式提取之前的一些战术角色替换是有序的,我倾向于"思考" stringi
用于矢量化替换stringr
(尽管stringr
对矢量化替换具有基本支持并且实际上stringi
在封面下使用):
library(stringi)
mytext <- c("Compared with 3 months earlier . . . . . . . . 123 (100.0) 11 (8 .9 60 (48. 8) 48 (39.0) 4 (3.3) . . . . . . . . . . . . . .",
"Compared with 3 months earlier . . . . . . . . 124 ( 100.0) 18 (14. 5) 60 (48.4) 42 (33 .9) 4 (3. 2) . . . . . . . . . . . . . .",
"Compared with 3 months earlier . . . . . . . . 124 (100.0) 7 (5.6) 42 (33.9) 64 (51.6) 11 (8.9) . . . . . . . . . . . . . .")
# vectorized cleanup
cleaned_text <- stri_replace_all_regex(mytext,
c(" \\.", "\\. ([:digit:])", "Compared with [[:digit:]]+ "),
c("", "\\.\\1", ""),
FALSE)
stri_extract_all_regex(cleaned_text, "[[:digit:]][[:digit:]\\.]*")
## [[1]]
## [1] "123" "100.0" "11" "89" "60" "48.1" "48" "39.0" "4" "3.3"
##
## [[2]]
## [1] "124" "100.0" "18" "14.1" "60" "48.4" "42" "339" "4" "3.1"
##
## [[3]]
## [1] "124" "100.0" "7" "5.6" "42" "33.9" "64" "51.6" "11" "8.9"
Run Code Online (Sandbox Code Playgroud)
希望您可以进行as.numeric()
任何其他重塑/转换.