Reputation: 295
I have a vector consisting of mixed double precision values and very short strings of characters. I want to sprintf
them, while showing results up to n
digits. The problem is, I can't sprintf
strings while using, for example sprintf("%.8g", x)
, so I am using "%.8s"
instead.
Because of that, if R writes the number in scientific notation, I am printing only beginning of the number and the results makes no sense. Simple example of this behaviour below:
koza <- c( pi, " > ", 2.01645169344289e-05)
sprintf("%.8s", koza)
What I receive is:
[1] "3.141592" " > " "2.016451"
What I want to receive is either something like:
[1] "3.1415927" " > " "0.0000202"
or
[1] "3.1415927" " > " "2.0164517e-05"
How can I do that?
Upvotes: 0
Views: 1107
Reputation: 94182
Because you have mixed numbers and strings in this vector:
koza <- c( pi, " > ", 2.01645169344289e-05)
R has converted them all to character strings:
> koza
[1] "3.14159265358979" " > " "2.01645169344289e-05"
So printing with a "%s"
formatter will format it as a string, and so you'll only get the first N characters of "2.01645169344289e-05"
.
> sprintf("%.4s", "abcdefghij")
[1] "abcd"
> sprintf("%.4s", koza)
[1] "3.14" " > " "2.01"
You need to keep them as numeric as much as possible, format them as decimal numbers, and then paste them into strings.
Upvotes: 1