R语言 我只想检索数值

kiz8lqtg  于 2023-01-22  发布在  其他
关注(0)|答案(4)|浏览(115)
vector<-c("0.78953744969927742", "0.46557689748480685", "0.19740881059705201", 
  "9.7073839462985714E-2", "4.9051709747422199E-2", "0.1167420589551126", 
  "0.12679434401288708", "0.51370748568563795", "0.1925345466801483", 
  "0.48287163643195624", "4.211984449707315E-2", "blablablab", 
  "0.10553766233766231", "7.8187250996015922E-2", "0.20718689788053954", 
  "1.6450511945392491E-2", "0.51752961082910309", "0.10978571428571428", 
  "0.42610062893081763", "0.52208333333333334", "0.27569868995633184", 
  "7.7189939288811793E-2", "0.53982300884955747", "38.25% (blablabla) blablablablablablablablablablablabla","0.22324159021406728")

我必须把所有的观察结果转换成数值。那些只由NA中的单词组成的。如果在一个以数字开头的观察结果之后有单词;仅检索数字。如果数字后有百分比,则删除这些百分比并仅保留数字

xt0899hw

xt0899hw1#

带有readrparse_number

library(readr)

vec_num <- parse_number(vector)
Warning: 1 parsing failure.
row col expected     actual
 12  -- a number blablablab

vec_num
 [1]  0.78953745  0.46557690  0.19740881  0.09707384  0.04905171  0.11674206
 [7]  0.12679434  0.51370749  0.19253455  0.48287164  0.04211984          NA
[13]  0.10553766  0.07818725  0.20718690  0.01645051  0.51752961  0.10978571
[19]  0.42610063  0.52208333  0.27569869  0.07718994  0.53982301 38.25000000
[25]  0.22324159
attr(,"problems")
# A tibble: 1 × 4
    row   col expected actual    
  <int> <int> <chr>    <chr>     
1    12    NA a number blablablab

vec_num[24]
[1] 38.25
dxxyhpgq

dxxyhpgq2#

清除所有垃圾

> as.numeric(gsub("[^0-9\\.\\E\\-]","",vector))
 [1]  0.78953745  0.46557690  0.19740881  0.09707384  0.04905171  0.11674206
 [7]  0.12679434  0.51370749  0.19253455  0.48287164  0.04211984          NA
[13]  0.10553766  0.07818725  0.20718690  0.01645051  0.51752961  0.10978571
[19]  0.42610063  0.52208333  0.27569869  0.07718994  0.53982301 38.25000000
[25]  0.22324159
3b6akqbq

3b6akqbq3#

您可以使用

as.numeric(stringr::str_extract(vector, '[\\d+.\\-\\E]+'))
uklbhaso

uklbhaso4#

这有点取决于regexp的具体类型,但这就足够了:

\d+(.\d+(E[+-]\d+)?)

请访问www.example.com进行检查和优化regex101.com

相关问题