繁体   English   中英

从 R 中的字符向量中提取数字和下一个字符串

[英]Extract digits and next string after from a character vector in R

我正在尝试解决一个问题。 我有一个文本向量,我想从中提取数字和下一个字符(包括空格)。 我正在为 R 使用 stringr package,但我似乎无法为我的问题找到一个好的解决方案。 感谢您的帮助/反馈。

library(tidyverse)
library(stringr)

my_text <- "This is my example vector. I have 15 oranges in the fridge, 12 apples in the room, 1 mother in my family, 1 father in my family, 12 siblings that live on 3 continents, and 45 randomthingsinmyhouse that I dont use"

#I would like to get the following information from my_text

"15 oranges" "12 apples" "1 mother" "1 father" "12 siblings" "45 randomthingsinmyouse"

str_extract_all(my_text, "\\d+")

"15" "12" "1" "1" "12" "45"

我曾尝试使用 str_extract_all(my_text, "\\d+") 但显然这只抓取数字。 我尝试在 stringr package 帮助页面上使用不同的正则表达式模式(https://stringr.tidyverse.org/articles/regular-expressions.ZFC35FDC70D5FC69D239883A822C似乎可以解决我的问题) 数字后面的文字也可以是随机的——我可以用鸡、房子等代替苹果和橘子。 关于我应该如何解决这个问题的任何建议?

非常感谢

使用该模式匹配一个或多个数字 ( \\d+ ),后跟一个或多个空格 ( \\s+ ) 和单词 ( \\w+ )

library(stringr)
str_extract_all(my_text, "\\d+\\s+\\w+")[[1]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM