发布
社区首页 >问答首页 >如何从R中的字符串中提取零件

如何从R中的字符串中提取零件
EN

Stack Overflow用户
提问于 2014-03-12 02:52:06
回答 4查看 295关注 0票数 1

当我尝试获取R中的数字部分时,我遇到了一个问题。例如,原始字符串是"buy 1000 shares of Google at 1100 GBP"

我需要分别提取股票数量(1000)和价格(1100)。此外,我需要提取股票的编号,它总是出现在"shares of"之后。

我知道subgsub可以替换字符串,但是我应该使用什么命令来提取字符串的一部分呢?

EN

回答 4

Stack Overflow用户

发布于 2014-03-12 02:55:43

1)此命令按顺序提取所有数字:

代码语言:javascript
代码运行次数:0
复制
s <- "buy 1000 shares of Google at 1100 GBP"

library(gsubfn)
strapplyc(s, "[0-9.]+", simplify = as.numeric)

给予:

代码语言:javascript
代码运行次数:0
复制
[1] 1000 1100

2)如果数字可以是任意顺序,但如果股票数量后面总是跟着单词" shares“,价格后面总是跟着英镑,那么:

代码语言:javascript
代码运行次数:0
复制
strapplyc(s, "(\\d+) shares", simplify = as.numeric) # 1000
strapplyc(s, "([0-9.]+) GBP", simplify = as.numeric) # 1100

返回与括号内的正则表达式部分匹配的字符串部分。

3)如果字符串的形式是已知的:在Z GBP时Y的X份额,则可以像这样提取X、Y和Z:

代码语言:javascript
代码运行次数:0
复制
strapplyc(s, "(\\d+) shares of (.+) at ([0-9.]+) GBP", simplify = c)

添加了修改过的图案,以允许数字或点。还添加了上面的(3)和以下内容:

代码语言:javascript
代码运行次数:0
复制
strapply(c(s, s), "[0-9.]+", as.numeric)
strapply(c(s, s), "[0-9.]+", as.numeric, simplify = rbind) # if ea has same no of matches

strapply(c(s, s), "(\\d+) shares", as.numeric, simplify = c)
strapply(c(s, s), "([0-9.]+) GBP", as.numeric, simplify = c)

strapplyc(c(s, s), "(\\d+) shares of (.+) at ([0-9.]+) GBP")
strapplyc(c(s, s), "(\\d+) shares of (.+) at ([0-9.]+) GBP", simplify = rbind)
票数 2
EN

Stack Overflow用户

发布于 2014-03-12 03:16:39

您可以使用sub函数:

代码语言:javascript
代码运行次数:0
复制
s <- "buy 1000 shares of Google at 1100 GBP"

# the number of shares
sub(".* (\\d+) shares.*", "\\1", s)
# [1] "1000"

# the stock
sub(".*shares of (\\w+) .*", "\\1", s)
# [1] "Google"

# the price
sub(".* at (\\d+) .*", "\\1", s)
# [1] "1100"

您还可以使用gregexprregmatches一次提取所有子字符串:

代码语言:javascript
代码运行次数:0
复制
regmatches(s, gregexpr("\\d+(?= shares)|(?<=shares of )\\w+|(?<= at )\\d+", 
                       s, perl = TRUE))
# [[1]]
# [1] "1000"   "Google" "1100"  
票数 1
EN

Stack Overflow用户

发布于 2014-03-12 03:56:27

我觉得有必要把强制性的stringr解决方案也包括进来。

代码语言:javascript
代码运行次数:0
复制
library(stringr)

s <- "buy 1000 shares of Google at 1100 GBP"

str_match(s, "([0-9]+) shares")[2]
[1] "1000"

str_match(s, "([0-9]+) GBP")[2]
[1] "1100"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22334028

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档