Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print number as word if less than 10

Tags:

r

latex

knitr

Consider this code:

sample(1:20, 1)

If the result happens to be less than or equal to 10, can I get R to print out the number as a word. For example, if the result of sample(1:20, 1) is 2, can I program R to print the result as two, if the result of sample(1:20, 1) is 10, can I program R to print the result as ten, if the result of sample(1:20, 1) is 13, can I program R to print the result as 13, and so on.

I am using knitrto convert R code to latex for my thesis. My rule is any number less than or equal to 10 should be printed as word.

like image 461
luciano Avatar asked Feb 09 '14 10:02

luciano


1 Answers

You can use the english package to transform numbers into English words:

set.seed(1)
s <- sample(1:20, 10)
# [1]  6  8 11 16  4 14 15  9 19  1

library(english)
ifelse(s > 10, s, as.character(english(s)))
# [1] "six"   "eight" "11"    "16"    "four"  "14"    "15"    "nine"  "19"    "one"
like image 200
Sven Hohenstein Avatar answered Nov 09 '22 14:11

Sven Hohenstein