基本上,我有以下说法:
counter <- 3
k <- 9999
我想让 R 打印以下内容:
on the 3rd count: 9999
有没有人我应该使用什么命令来做到这一点?请为我拼写出来,因为我对 R 完全陌生。
最佳答案
基本 build 是
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
在字符串之间插入一个空格。
关于r - 如何连接字符串和从 R 中的函数计算的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13036649/