R从字符串中提取第一个数字

kne*_*ijs 12 regex r gsub strsplit

我在变量中有一个字符串,我们称之为v1.该字符串表示图片编号,采用"Pic 27 + 28"的形式.我想提取第一个数字并将其存储在一个名为item的新变量中.

我尝试过的一些代码是:

item <- unique(na.omit(as.numeric(unlist(strsplit(unlist(v1),"[^0-9]+")))))
Run Code Online (Sandbox Code Playgroud)

这很好,直到我找到了一个列表:

[1,] "Pic 26 + 25"
[2,] "Pic 27 + 28"
[3,] "Pic 28 + 27"
[4,] "Pic 29 + 30"
[5,] "Pic 30 + 29"
[6,] "Pic 31 + 32"
Run Code Online (Sandbox Code Playgroud)

在这一点上,我获得了比我想要的更多的数字,因为它也抓住了其他唯一的数字(25).

我实际上尝试过使用gsub,但没有任何工作.帮助将非常感激!

gag*_*ews 12

我假设您想要提取每个字符串中的两个数字中的第一个.

您可以使用stringi包中的stri_extract_first_regex函数:

library(stringi)
stri_extract_first_regex(c("Pic 26+25", "Pic 1,2,3", "no pics"), "[0-9]+")
## [1] "26" "1"  NA  
Run Code Online (Sandbox Code Playgroud)


G. *_*eck 6

在下面的响应中,我们使用此测试数据:

# test data
v1 <- c("Pic 26 + 25", "Pic 27 + 28", "Pic 28 + 27", "Pic 29 + 30", 
"Pic 30 + 29", "Pic 31 + 32")
Run Code Online (Sandbox Code Playgroud)

1)gsubfn

library(gsubfn)

strapply(v1, "(\\d+).*", as.numeric, simplify = c)
## [1] 26 27 28 29 30 31
Run Code Online (Sandbox Code Playgroud)

2) sub 这不需要包,但涉及稍长的正则表达式:

as.numeric( sub("\\D*(\\d+).*", "\\1", v1) )
## [1] 26 27 28 29 30 31
Run Code Online (Sandbox Code Playgroud)

3) read.table 这里不涉及正则表达式或包:

read.table(text = v1, fill = TRUE)[[2]]
## [1] 26 27 28 29 30 31
Run Code Online (Sandbox Code Playgroud)

在此特定示例中,fill=TRUE可以省略,但如果 的组件v1具有不同数量的字段,则可能需要它。


avi*_*seR 5

str_extract来自stringr

library(stringr)

vec = c("Pic 26 + 25", "Pic 27 + 28", "Pic 28 + 27", 
        "Pic 29 + 30", "Pic 30 + 29", "Pic 31 + 32")

str_extract(v1, "[0-9]+")
# [1] "26" "27" "28" "29" "30" "31"
Run Code Online (Sandbox Code Playgroud)