简体   繁体   中英

How to convert a numeric vector to a character vector as the numeric vector is printed to the screen?

R> pretty(c(-1.2, 1.2), 12)
 [1] -1.2 -1.0 -0.8 -0.6 -0.4 -0.2  0.0  0.2  0.4  0.6  0.8  1.0  1.2
R> as.character(pretty(c(-1.2, 1.2), 12))
 [1] "-1.2" "-1"   "-0.8" "-0.6" "-0.4" "-0.2" "0"    "0.2"  "0.4"  "0.6"  "0.8"  "1"    "1.2"

as.character() does not convert a numeric vector as it is printed to the screen. How to get what is printed to the screen as a character vector?

For this example, I need the results to be c("-1.2", "-1.0", ...) . But the solution should not be based on a format specific to this problem. It should be general so that any numeric array can be converted the character array as it is printed to the screen.

I think you want format , which is what print uses internally.

format(pretty(c(-1.2, 1.2), 12), trim = T)

[1] "-1.2" "-1.0" "-0.8" "-0.6" "-0.4" "-0.2" "0.0"  "0.2"  "0.4" 
[10] "0.6"  "0.8"  "1.0"  "1.2" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM