Below are the solutions to these exercises on “Pro-grammatically Creating Text Outputs in R.”
#################### # # # Exercise 1 # # # #################### prices <- c( 14.3409087337707, 13.0648270623048, 3.58504267621646, 18.5077076398145, 16.8279241011882 ) sprintf("$%.2f", prices)
## [1] "$14.34" "$13.06" "$3.59" "$18.51" "$16.83"
#################### # # # Exercise 2 # # # #################### fn <- c(25, 7, 90, 16) sprintf("file_%03d.txt", fn)
## [1] "file_025.txt" "file_007.txt" "file_090.txt" "file_016.txt"
#################### # # # Exercise 3 # # # #################### fn <- c(25, 7, 90, 16) sprintf("file_%0*d.txt", nchar(max(fn)), fn)
## [1] "file_25.txt" "file_07.txt" "file_90.txt" "file_16.txt"
#################### # # # Exercise 4 # # # #################### poeml <- c("Stay the patient course.", "Of little worth is your ire.", "The network is down.") nmax <- max(nchar(poeml)) cat(sprintf("%*s", nmax, poeml), sep = "\n")
## Stay the patient course. ## Of little worth is your ire. ## The network is down.
#################### # # # Exercise 5 # # # #################### tohex <- function(x) { sprintf("%1$d is %1$x in hexadecimal", x) } tohex(12)
## [1] "12 is c in hexadecimal"
#################### # # # Exercise 6 # # # #################### title <- "A great poem" sprintf("<h1>%s</h1>", title)
## [1] "<h1>A great poem</h1>"
# shiny::h1(title) #################### # # # Exercise 7 # # # #################### library(magrittr) poeml %>% sprintf("<li>%s</li>", .) %>% paste(., collapse = " ") %>% sprintf("<ul>%s</ul>", .)
## [1] "<ul><li>Stay the patient course.</li> <li>Of little worth is your ire.</li> <li>The network is down.</li></ul>"
#################### # # # Exercise 8 # # # #################### text_list <- function(x) { n <- length(x) if (n <= 1) { return(x) } paste(paste(x[-n], collapse = ", "), "and", x[n]) } films <- c("The Shawshank Redemption", "The Godfather", "The Godfather: Part II", "The Dark Knight", "12 Angry Men", "Schindler's List") sprintf("The top ranked films on imdb.com are %s", text_list(films))
## [1] "The top ranked films on imdb.com are The Shawshank Redemption, The Godfather, The Godfather: Part II, The Dark Knight, 12 Angry Men and Schindler's List"
#################### # # # Exercise 9 # # # #################### perc <- function(x, dp) { sprintf("%.*f%%", dp, x*100) } input <- 0.921313 perc(input, 2)
## [1] "92.13%"
#################### # # # Exercise 10 # # # #################### perc2 <- function(x, dp) { p <- sprintf("%.*f%%", dp, x*100) if(any(nchar(p) > 10)) stop("Too long percentage") sprintf("%10s", p) } set.seed(1) cat(perc2(rnorm(10), 1), sep="\n")
## -62.6% ## 18.4% ## -83.6% ## 159.5% ## 33.0% ## -82.0% ## 48.7% ## 73.8% ## 57.6% ## -30.5%
perc2(999, 4)
## Error in perc2(999, 4): Too long percentage
Leave a Reply