2015-09-05 44 views
1

提取數字我有一系列的字符串如下:與單位從字符串

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" 

感謝您閱讀

+0

將總是存在範圍之間的'和'或一個'to'? – hrbrmstr

+0

嘗試庫(stringr); do.call(rbind,lapply(str_extract_all(x,'\\ d +(\\ s + | cm \\ b |%)'),function(x){m1 < - matrix(x ,ncol = 2,byrow = TRUE); paste(m1 [,1],m1 [,2])}))' – akrun

回答

2

我們可以使用從library(stringr)str_extract_all提取匹配模式(改性從@PierreLafortune評論)的元素

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" 
+0

@ user3857437可以提取不同的模式。我的代碼基於OP發佈的示例。 – akrun

+0

並不總是一個和或之間的數字範圍,我完成了我所需要的以下內容: x < - str_extract_all(x,'\\ d +?(cm |%| mm)??(to |和| [:punct:])??(\\ d +)?(cm |%| mm)?') x < - lapply(x,function(x){gsub(「and | to」 「 - 」 中,x)}) X <-rbind.fill(lapply(草地,函數(Y {as.data.frame(T(Y),stringsAsFactors = FALSE)})) 感謝您的快速回答 – user3857437

+0

@ user3857437感謝您的反饋。 – akrun

0

不是特別優雅,但...

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