In the age of Rmarkdown and Shiny, or when making any custom output from your data, you want your output to look consistent and neat. Also, when writing your output, you often want it to obtain a specific (decorative) format defined by the html or LaTeX engine. These exercises are an opportunity to refresh our memory on functions, such as paste, sprintf, formatC and others that are convenient tools to achieve these ends. All of the solutions rely partly on the ultra flexible sprintf(), but there are no-doubt many ways to solve the exercises with other functions. Feel free to share your solutions in the comment section.
Example solutions are available here.
Exercise 1
Print out the following vector as prices in dollars (to the nearest cent):
c(14.3409087337707, 13.0648270623048, 3.58504267621646, 18.5077076398145,
. Example:
16.8279241011882)$14.34
Exercise 2
Using these numbers, c(25, 7, 90, 16)
, make a vector of filenames in the following format: file_025.txt
. Left pad the numbers so they are all three digits.
Exercise 3
Actually, if we are only dealing with numbers less than one hundred, file_25.txt
would have been enough. Change the code from the last exercise so that the padding is pro-grammatically decided by the biggest number in the vector.
Exercise 4
Print out the following haiku on three lines, right aligned, with the help of cat: c("Stay the patient course.", "Of little worth is your ire.", "The network is down.")
.
Exercise 5
Write a function that converts a number to its hexadecimal representation. This is a useful skill when converting bmp colors from one representation to another. Example output:
tohex(12) [1] "12 is c in hexadecimal"
Exercise 6
Take a string and pro-grammatically surround it with the html header tag h1
.
Exercise 7
Back to the poem from exercise 4, let R convert to html unordered list so that it would appear like the following in a browser:
- Stay the patient course
- Of little worth is your ire
- The network is down
Exercise 8
Here is a list of the current top 5 movies on imdb.com in terms of rating c("The Shawshank Redemption", "The Godfather", "The Godfather: Part II", "The Dark Knight", "12 Angry Men", "Schindler's List")
. Convert them into a list compatible with the written text.
Example output:
[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
Now, you should be able to solve this quickly: write a function that converts a proportion to a percentage that takes as input number of decimal places. An input of 0.921313 and 2 decimal places should return "92.13%"
.
Exercise 10
Improve the function from the last exercise so that the percentage consistently takes 10 characters by doing some left padding. Raise an error if the percentage already happens to be longer than 10.
(Image by Daniel Friedman).
glæsilegt. flott.
takk.