用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(),但它没有给我预期的结果。

在正则表达式提取之前进行一些战术字符替换是有序的,我倾向于在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()和任何其他重塑/转换

类似于@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"  

最新更新