2016-08-02 58 views
0

假裝的字符串我有一個向量:提取了一些長短不一

testVector <- c("I have 10 cars", "6 cars", "You have 4 cars", "15 cars") 

有沒有一種方法去分析這個矢量,所以我可以只存儲數值:

10, 6, 4, 15 

如果問題只是「15輛汽車」和「6輛汽車」,我知道如何解析,但我對前面帶有文字的字符串也有困難!任何幫助是極大的讚賞。

回答

3

我們可以使用str_extract的模式\\d+這意味着匹配一個或多個數字。它可以寫成[0-9]+

library(stringr) 
as.numeric(str_extract(testVector, "\\d+")) 
#[1] 10 6 4 15 

如果有一個字符串多個號碼,我們使用str_extract_all其返回永存一個list輸出。


這也可以用base R(無外部使用的包)

as.numeric(regmatches(testVector, regexpr("\\d+", testVector))) 
#[1] 10 6 4 15 

或者使用gsubbase R

as.numeric(gsub("\\D+", "", testVector)) 
#[1] 10 6 4 15 

BTW做,有些功能只是用gsub,從extract_numeric

function (x) 
{ 
    as.numeric(gsub("[^0-9.-]+", "", as.character(x))) 
} 

所以,如果我們需要一個功能,我們可以創建一個(不使用任何外部包裝)

ext_num <- function(x) { 
      as.numeric(gsub("\\D+", "", x)) 
     } 
ext_num(testVector) 
#[1] 10 6 4 15 
+0

謝謝!你能幫我描述一下「\\ d +」是什麼意思嗎? – Sheila

+0

@Sheila更新了帖子 – akrun

+3

正則表達式https://www.cheatography.com/davechild/cheat-sheets/regular-expressions/ – Nate

5

對於這個特殊的共同任務,有一個在tidyr一個不錯的輔助函數稱爲extract_numeric

library(tidyr) 

extract_numeric(testVector) 
## [1] 10 6 4 15 
1

這也可能派上用場。

testVector <- gsub("[:A-z:]","",testVector) 
testVector <- gsub(" ","",testVector) 

> testVector 
[1] "10" "6" "4" "15"