Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the number from character "\n 0.28\n \n " in R language

Tags:

r

I would like to get the 0.28 from the character using R "\n 0.28\n \n ".

Maybe I should use sub() function, but I am not sure how to do it.

like image 305
zhenhao Avatar asked Dec 01 '25 11:12

zhenhao


2 Answers

In general, you want to learn about regular expressions. Which can be intimidating, but you can also learn by example.

Here, we can do something relatively simple:

R> txt <- "\n 0.28\n \n "
R> gsub(".* ([0-9.]+).*", "\\1", txt)
[1] "0.28"
R> as.numeric(gsub(".* ([0-9.]+).*", "\\1", txt))
[1] 0.28
R> 

The (...) marks something we "want", here we say we want digits or dots, and several of them (the +). The "\\1" then recalls that match.

Alternatively, we could just "erase" all of the \n and spaces:

R> as.numeric(gsub("[\n ]", "", txt))
[1] 0.28
R> 
like image 54
Dirk Eddelbuettel Avatar answered Dec 03 '25 03:12

Dirk Eddelbuettel


You don't need regular expressions for your use-case.

 string <-  "\n 0.28\n \n "
 as.numeric(string)
 [1] 0.28
like image 44
hd1 Avatar answered Dec 03 '25 04:12

hd1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!