如何用数字模式拆分数字字符串?

数据挖掘 数据争吵
2022-02-19 08:05:11

我正在尝试将数字字符串拆分为两位数

如何从该字符串中获取两个不同的数字

例子:

我想要分开的两个数字

x <- c("-26755.22-50150.60") 

对此

-26755.22
-50150.60 

我已经尝试过stringr::str_split,但我无法保留数字。

2个回答

我刚做了这个-

> library(stringr)
> x <- c("-26755.22-50150.60")
> matc = "\\-[0-9]*\\.[0-9]{2}"
> as.numeric(unlist(str_match_all(x, matc)))
[1] -26755.22 -50150.60

在此之后,您可以使用相应的索引来选择数字。

我认为这应该为你做的事情:

#the input
str <- " -26755.22-50150.60"    


#you can use this command to split the data into 2 columns
#this doesn't have any constraint in the number of digits before and after the decimal
strspl <- as.numeric(unlist(regmatches(str,gregexpr("(?>-)*[[:digit:]]+\\.*[[:digit:]]*",str, perl=TRUE))))

结果:

> strspl
[1] -26755.22 -50150.60

如果要将结果存储在数据框中,则可以使用以下命令

#everything is same but instead of as.numeric we replace it with as.data.frame
str_df <- as.data.frame(unlist(regmatches(str,gregexpr("(?>-)*[[:digit:]]+\\.*[[:digit:]]*",str, perl=TRUE))))

#it is not necessary to change the column but it is a good practice to do so
colnames(str_df) <- "variable_1"

结果:

数据框中的结果

如果您有任何疑问,请告诉我,对您有帮助。

如果你得到了你要找的东西,你可以通过点击绿色的勾号来接受答案。