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

问题描述 投票:12回答:5

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

我尝试过的一些代码是:

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

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

[1,] "Pic 26 + 25"
[2,] "Pic 27 + 28"
[3,] "Pic 28 + 27"
[4,] "Pic 29 + 30"
[5,] "Pic 30 + 29"
[6,] "Pic 31 + 32"

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

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

regex r gsub strsplit
5个回答
12
投票

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

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

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

3
投票

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

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

1)gsubfn

library(gsubfn)

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

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

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

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

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

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


3
投票

您可以使用str_first_number()包中的strex函数非常好地完成此操作,或者对于更一般的需求,您可以使用str_nth_number()函数。用install.packages("strex")安装它。

library(strex)
#> Loading required package: stringr
strings <- c("Pic 26 + 25", "Pic 27 + 28", "Pic 28 + 27",
             "Pic 29 + 30", "Pic 30 + 29", "Pic 31 + 32")
str_first_number(strings)
#> [1] 26 27 28 29 30 31
str_nth_number(strings, n = 1)
#> [1] 26 27 28 29 30 31

1
投票

跟进你的strsplit尝试:

# split the strings
l <- strsplit(x = c("Pic 26 + 25", "Pic 27 + 28"), split = " ")
l
# [[1]]
# [1] "Pic" "26"  "+"   "25" 
# 
# [[2]]
# [1] "Pic" "27"  "+"   "28" 

# extract relevant part from each list element and convert to numeric
as.numeric(lapply(l , `[`, 2))
# [1] 26 27

1
投票

来自str_extractstringr

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"
© www.soinside.com 2019 - 2024. All rights reserved.