英文:
Extract only digits and full stop from string
问题
我只想保留数字和小数点。是否有解决方案?感谢您的帮助。
英文:
I have following strings :
x <- c("3 333.33!", "1 002 22??", "232.23x")
I only want to keep numbers and dots.
is there a solution?
Thanks for your help
答案1
得分: 2
We could just extract any digits and full stops and then collapse the string again.
library(stringr)
sapply(str_extract_all(x, "[:digit:]|\\."), function(x) str_c(x, collapse=""))
"3333.33" "100222" "232.23"
英文:
We could just extract any digits and full stops and then collapse the string again.
library(stringr)
sapply(str_extract_all(x, "[:digit:]|\\."), function(x) str_c(x, collapse=""))
"3333.33" "100222" "232.23"
答案2
得分: 2
删除空格(正则表达式 " +"
表示“一个或多个空格”),然后调用 readr::parse_number()
,它会忽略除了 .-
之外的字母字符/标点符号。
x |> stringr::str_remove(" +") |> readr::parse_number()
英文:
Remove whitespace (regex " +"
means "one or more spaces") and then call readr::parse_number()
, which ignores alphabetic characters/punctuation other than .-
x |> stringr::str_remove(" +") |> readr::parse_number()
答案3
得分: 1
在基本的 R 语言中:
gsub("[^0-9.]", "", x)
[1] "3333.33" "100222" "232.23"
如果你需要它们作为数字:
```R
as.numeric(gsub("[^0-9.]", "", x))
[1] 3333.33 100222.00 232.23
英文:
in base R:
gsub("[^0-9.]", "", x)
[1] "3333.33" "100222" "232.23"
if you need them as numeric:
as.numeric(gsub("[^0-9.]", "", x))
[1] 3333.33 100222.00 232.23
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论