r语言怎么提取字符串中的数字

在R语言中,可以使用正则表达式来提取字符串中的数字。具体的方法有两种:

使用str_extract()函数和正则表达式来提取字符串中的数字。

library(stringr)
string <- "Hello123World456"
numbers <- str_extract(string, "\\d+")

在上述代码中,str_extract()函数用于提取字符串中的数字。正则表达式\\d+表示匹配连续的数字字符。

使用str_extract_all()函数和正则表达式来提取字符串中的所有数字。

library(stringr)
string <- "Hello123World456"
numbers <- unlist(str_extract_all(string, "\\d+"))

在上述代码中,str_extract_all()函数用于提取字符串中的所有数字。unlist()函数用于将提取结果转换为向量。

无论使用哪种方法,最后可以通过打印numbers变量来查看提取的数字。

阅读剩余
THE END