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.
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
The solutions so far are great and actually teach you something. If you want the dumb but simple answer, taRifx::destring
will work:
library(taRifx)
> destring("\n 0.28\n \n ")
[1] 0.28
It uses the [^...]
regular expression idiom ("not") rather than back-referencing as in @Dirk's solution:
return(as.numeric(gsub(paste("[^", keep, "]+", sep = ""), "", x)))