Type the number as a word if it is less than 10

Consider this code:

sample(1:20, 1) 

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

I use knitr to convert R code to latex for my dissertation. My rule is that any number less than or equal to 10 should be printed as a word.

+7
r knitr latex
source share
3 answers

You can use the english package to convert numbers to 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" 
+12
source share

Essentially, this is the same as Marks, but a bit more concise:

 numbers = c('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten') readable = function (x) ifelse(x < 11, numbers[x + 1], x) 
 > readable(sample(1:20, 10)) [1] "20" "12" "13" "seven" "ten" "11" "17" "eight" "16" "18" 

Although if you are using knitr with LaTeX, this is probably the task for LaTeX and not for R: R provides raw data, LaTeX is responsible for formatting. I will probably just say that knitr will output the numbers enclosed inside the macro - \readable{42} - and then do the conversion with this macro (unchecked and requires the siunitx package):

 \newcommand*\readable[1]{% \ifcase#1 zero\or one\or two\or three\or four\or five\or six\or seven\or eight\or nine\or ten\else\num{#1}} 
+6
source share

It is not elegant, but I think he will do what you want.

 set.seed(1234) x <- sample(1:20, 1) my.data <- read.table(text=' xy 0 zero 1 one 2 two 3 three 4 four 5 five 6 six 7 seven 8 eight 9 nine 10 ten ', header = TRUE) if(x > 10) {y = x} else {y = my.data$y[x == my.data$x]} data.frame(x, y) xy 1 3 three 

Here is a way to convert multiple numbers at once:

 set.seed(1234) x <- sample(1:20, 10) x <- as.data.frame(x) my.data <- read.table(text=' xy 0 zero 1 one 2 two 3 three 4 four 5 five 6 six 7 seven 8 eight 9 nine 10 ten ', header = TRUE, stringsAsFactors = FALSE) y <- apply(x, 1, function(i) if(i > 10) {y = i} else {y = my.data$y[i == my.data$x]}) data.frame(x, y) xy 1 3 three 2 12 12 3 11 11 4 18 18 5 14 14 6 10 ten 7 1 one 8 4 four 9 8 eight 10 6 six 
+2
source share

All Articles