r語(yǔ)言怎么提取字符串中的數(shù)字

小億
295
2024-01-12 02:54:03

在R語(yǔ)言中,可以使用正則表達(dá)式來(lái)提取字符串中的數(shù)字。具體的方法有兩種:

  1. 使用str_extract()函數(shù)和正則表達(dá)式來(lái)提取字符串中的數(shù)字。
library(stringr)
string <- "Hello123World456"
numbers <- str_extract(string, "\\d+")

在上述代碼中,str_extract()函數(shù)用于提取字符串中的數(shù)字。正則表達(dá)式\\d+表示匹配連續(xù)的數(shù)字字符。

  1. 使用str_extract_all()函數(shù)和正則表達(dá)式來(lái)提取字符串中的所有數(shù)字。
library(stringr)
string <- "Hello123World456"
numbers <- unlist(str_extract_all(string, "\\d+"))

在上述代碼中,str_extract_all()函數(shù)用于提取字符串中的所有數(shù)字。unlist()函數(shù)用于將提取結(jié)果轉(zhuǎn)換為向量。

無(wú)論使用哪種方法,最后可以通過(guò)打印numbers變量來(lái)查看提取的數(shù)字。

0