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
变量来查看提取的数字。
TOP