【发布时间】:2012-10-23 18:15:00
【问题描述】:
基本上,我有以下说法:
counter <- 3
k <- 9999
我想让 R 打印以下内容:
on the 3rd count: 9999
有没有人我应该使用什么命令来做到这一点?请为我拼写出来,因为我对 R 完全陌生。
【问题讨论】:
标签: r statistics
基本上,我有以下说法:
counter <- 3
k <- 9999
我想让 R 打印以下内容:
on the 3rd count: 9999
有没有人我应该使用什么命令来做到这一点?请为我拼写出来,因为我对 R 完全陌生。
【问题讨论】:
标签: r statistics
基本结构是
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 在字符串之间插入一个空格。
【讨论】:
suffixSelector!)
使用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 是这里真正的坏演员)将它们全部发送到包含 "th" 的 suffix 的元素.
【讨论】: