基本上,我有以下说法:
counter <- 3
k <- 9999
我想让 R 打印以下内容:
on the 3rd count: 9999
有谁我应该使用什么命令来做到这一点?请为我拼写出来,因为我对 R 完全陌生。
基本上,我有以下说法:
counter <- 3
k <- 9999
我想让 R 打印以下内容:
on the 3rd count: 9999
有谁我应该使用什么命令来做到这一点?请为我拼写出来,因为我对 R 完全陌生。
基本结构是
paste("on the ", counter, "rd count: ", k, sep="")
您必须有点聪明才能为数字选择正确的后缀(即 3 后的“rd”,4-9 后的“th”等。这是一个功能:
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"
}
}
因此:
suffix <- suffixSelector(counter)
paste("on the ", counter, suffix, " count: ", k, sep="")
您需要设置sep
参数,因为默认情况下paste
会在字符串之间插入一个空格。
采用sprintf
> sprintf("on the %drd count: %d", counter, k)
[1] "on the 3rd count: 9999"
这是一种将每个整数与适当的后缀挂钩的稍微不同的方法。如果你把它分开,你会发现它确实捕获了构造每个整数的序数形式的句法(?)规则。
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"
一个解释性说明:需要该10*(((x %% 100) %/% 10) == 1)
位来挑选以 10 到 19 结尾的数字(11、12 和 13 是这里真正的坏演员)将它们全部发送到 contains 的suffix
元素"th"
。