2015-10-04 44 views
2

想知道是否有人可以帮我解决这个问题。下面有这个数据。在R中提取带小数点和空格的数字

[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) . . . . . . . . . . . . . ." 

想提取上面是这样

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 

有一些,哪些应该被视为一个单独的号码小数之间的一些随机的空间。我试图使用str_extract_all(),但它没有给我预期的结果。

+0

你用'str_extract_all()'尝试了什么,这个输出实际来自哪里?即它是否有'[1]','[2]','[3]'或者这只是R矢量的输出?来自'dput(variablename)'的输出优于来自'head','tail'或'print'的剪切/粘贴。 – hrbrmstr

+0

str_extract_all(mytext,“[0-9] +”)。想知道是否有快速修复。以上是R.的输出。mytext是上面输出的字符向量。 – qfd

+0

你是如何期待获得小数? – hrbrmstr

回答

4

类似于@hrbrmstr的方法。以hrbrmstr的示例(mytext),我做了以下。 gsub()部分处理您的空间问题。 .(space)(space).在代码中被替换为.。然后,stri_extract_all()提取所有数字。在你的情况下,你有几个月的数字,这是每个矢量中的第一个数字。 lapply(function(x){x[-1]})删除每个向量中的第一个数字。

library(stringi) 
library(magrittr) 

gsub(pattern = "\\.\\s|\\s\\.", replacement = "\\.", x = mytext) %>% 
stri_extract_all(regex = "\\d+\\.\\d+|\\d+") %>% 
lapply(function(x){x[-1]}) 


#[[1]] 
#[1] "123" "100.0" "11" "8.9" "60" "48.8" "48" "39.0" "4"  "3.3" 

#[[2]] 
#[1] "124" "100.0" "18" "14.5" "60" "48.4" "42" "33.9" "4"  "3.2" 

#[[3]] 
#[1] "124" "100.0" "7"  "5.6" "42" "33.9" "64" "51.6" "11" "8.9" 
+0

@qfd乐意帮助你。 :) – jazzurro

5

一些战术字符替换正则表达式提取之前是为了我倾向于“思考” 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" 

希望你可以做as.numeric()和任何其他重塑/转换。

+0

非常感谢哟!优秀。精美的作品。 – qfd