如何在 R 中将带有多个点的数字从字符转换为数字?

how to convert numbers with multiple dots inside from character to numeric in R?

我有一个向量 x 如下。

x= c("44.431.974.113.935", "-0.9780789132588046", "127.136.409.640.697", 
 "-5.510.222.665.234.440", "4.254.952.168.752.070", "0.9009379347023327")

棘手的部分是第一个点有意义,但其余的点没有意义。所以我需要把 x 取回

[1] 44.43 -0.97 127.13 -5.51 4.25 0.9

我尝试使用 gsub 但没有成功,并且找不到如何以跳过第一个点并删除其余点的方式编写 gsub。

必须有更漂亮的方法,但像这样的方法应该可行:

gsub("^(.*?[.].*)?[.].*", "\1", x)
## [1] "44.431"              "-0.9780789132588046" "127.136"            
## [4] "-5.510"              "4.254"               "0.9009379347023327" 

为数值换行 as.numeric

round(as.numeric(gsub("^(.*?[.].*)?[.].*", "\1", x)), 2)
## [1]  44.43  -0.98 127.14  -5.51   4.25   0.90

如果您想删除除第一个点之外的所有点,一个技巧可能是用逗号替换第一个点,删除点,然后用点替换逗号。类似于:

sub(",",".",gsub(".","",sub(".",",",x,fixed=TRUE),fixed=TRUE),fixed=TRUE)
#[1] "44.431974113935"     "-0.9780789132588046" "127.136409640697"   
#[4] "-5.510222665234440"  "4.254952168752070"   "0.9009379347023327"

然后你可以随意调用as.numericround

使用str_extract

library(stringr)
as.numeric(str_extract(x, '-*\d+\.[0-9]?[1-9]?'))
#[1]  44.43  -0.97 127.13  -5.51   4.25   0.90