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.
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>
You don't need regular expressions for your use-case.
string <- "\n 0.28\n \n "
as.numeric(string)
[1] 0.28
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With