【问题标题】:extracting numbers with units from string从字符串中提取带有单位的数字
【发布时间】:2015-09-05 10:39:34
【问题描述】:

我有一系列字符串如下:

x <- " 20 to 80% of the sward should be between 3 and 10cm tall, 
with 20 to 80% of the sward between 10 and 30cm tall"

我想提取数值并保留单位,我尝试了以下方法:

x <- lapply(x, function(x){gsub("[^\\d |cm\\b |mm\\b |% ]", "", x, perl = T)})

这给出了:

" 20  80%       3  10cm   20  80%     10  30cm "

我需要的是:

"20 80%" "3 10cm" "20 80%" "10 30cm" 

感谢阅读

【问题讨论】:

  • 范围之间是否总是存在andto
  • 试试library(stringr);do.call(rbind,lapply(str_extract_all(x, '\\d+(\\s+|cm\\b|%)'), function(x) {m1 &lt;- matrix(x, ncol=2, byrow=TRUE); paste(m1[,1], m1[,2])}))

标签: r gsub strsplit


【解决方案1】:

我们可以使用library(stringr)中的str_extract_all来提取匹配模式的元素(基于@PierreLafortune的cmets修改)

library(stringr)
lst <-  str_extract_all(x, '\\d+\\S*')

如果list元素的长度相同,我们可以rbind他们创建一个matrix

m1 <- do.call(rbind, lst)

paste 交替列在一起

v1 <- paste(m1[,c(TRUE, FALSE)], m1[,c(FALSE, TRUE)])

并将其转换回matrix

dim(v1) <- c(nrow(m1), ncol(m1)/2)
v1
#     [,1]     [,2]     [,3]     [,4]     
#[1,] "20 80%" "3 10cm" "20 80%" "10 30cm"

【讨论】:

  • @user3857437 您可以提取不同的模式。我的代码基于 OP 发布的示例。
  • 数字范围之间并不总是存在和或到,我通过以下方式完成了我所需要的:x
【解决方案2】:

不是特别优雅但是...

library(magrittr)
library(stringr)
library(dplyr)
library(plyr)
" 20  80%       3  10cm   20  80%     10  30cm " %>%
str_split(" ") %>%
unlist %>% 
as.data.frame %>% 
    plyr::rename(replace = c("." = "string")) %$%
    gsub(string, replacement = "", pattern = " ") %>%
    as.data.frame %>% 
    plyr::rename(replace = c("." = "string")) %>%
    filter(string != "") -> etc_etc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2020-03-11
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多