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

编程入门 行业动态 更新时间:2024-10-22 15:27:06
本文介绍了R从字符串中提取第一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have a string in a variable which we call v1. This string states picture numbers and takes the form of "Pic 27 + 28". I want to extract the first number and store it in a new variable called item.

我尝试过的一些代码是:

Some code that I've tried is:

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

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

This worked fine, until I came upon a list that went:

[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).

At this point I get more numbers than I want, as it is also grabbing other unique numbers (the 25).

我实际上已经尝试过使用gsub进行此操作,但没有任何效果.帮助将不胜感激!

I've actually tried doing it with gsub, but got nothing to work. Help would be appreciated greatly!

推荐答案

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

I assume that you'd like to extract the first of two numbers in each string.

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

You may use the stri_extract_first_regex function from the stringi package:

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

更多推荐

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

本文发布于:2023-10-27 18:49:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534234.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!