2012-10-23 8 views

risposta

12

La costruzione di base è

paste("on the ", counter, "rd count: ", k, sep="") 

dovrete essere un po 'intelligente per scegliere il suffisso giusto per la cifra (vale a dire " rd" dopo 3, "th" dopo 4-9, ecc Ecco una funzione per farlo:

suffixSelector <- function(x) { 
    if (x%%10==1) { 
    suffixSelector <- "st" 
    } else if(x%%10==2) { 
    suffixSelector <- "nd" 
    } else if(x%%10==3) { 
    suffixSelector <- "rd" 
    } else { 
    suffixSelector <- "th" 
    } 

}

Così:

suffix <- suffixSelector(counter) 
paste("on the ", counter, suffix, " count: ", k, sep="") 

È necessario impostare l'argomento sep poiché per impostazione predefinita paste inserisce uno spazio vuoto tra le stringhe.

+0

nice 'suffixSelector' +1 –

+0

Non funziona molto bene con 13, ad esempio ... Questo è un po 'più complicato di quanto sembri! (Inoltre, è necessario assicurarsi che il codice postato restituisca effettivamente il suffisso "selettore"!) –

+0

la funzione Incolla può essere inserita nel ciclo while? Perché non so perché niente viene stampato quando la pasta è nel ciclo while ??? – user1769197

1

Uso sprintf

> sprintf("on the %drd count: %d", counter, k) 
[1] "on the 3rd count: 9999" 
2

Ecco un approccio leggermente diverso per collegare ciascun numero intero con suffisso è opportuno. Se lo distingui, vedrai che cattura la regola sintattica (?) Per costruire la forma ordinale di ogni intero.

suffixPicker <- function(x) { 
    suffix <- c("st", "nd", "rd", rep("th", 17)) 
    suffix[((x-1) %% 10 + 1) + 10*(((x %% 100) %/% 10) == 1)] 
} 

## Testing with your example 
counter <- 3 
k <- 9999 
paste("on the ", paste0(counter, suffixPicker(counter)), 
     " count: ", k, sep="") 
# [1] "on the 3rd count: 9999" 

## Show that it also works for a range of numbers 
x <- 1:24 
paste0(x, suffixPicker(x)) 
# [1] "1st" "2nd" "3rd" "4th" "5th" "6th" "7th" "8th" "9th" "10th" 
# [11] "11th" "12th" "13th" "14th" "15th" "16th" "17th" "18th" "19th" "20th" 
# [21] "21st" "22nd" "23rd" "24th" 

Una nota esplicativa: è necessaria la 10*(((x %% 100) %/% 10) == 1) po 'di scegliere i numeri che terminano in 10 a 19 (11, 12, e 13 sono i veri cattivi attori qui) tutti loro invio a elementi di suffix contenenti "th".

Problemi correlati