【问题标题】:How do I concatenate String and an output evaluated from a function in R?如何连接字符串和从 R 中的函数评估的输出?
【发布时间】:2012-10-23 18:15:00
【问题描述】:

基本上,我有以下说法:

counter <- 3
k <- 9999

我想让 R 打印以下内容:

on the 3rd count: 9999 

有没有人我应该使用什么命令来做到这一点?请为我拼写出来,因为我对 R 完全陌生。

【问题讨论】:

    标签: r statistics


    【解决方案1】:

    基本结构是

    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 在字符串之间插入一个空格。

    【讨论】:

    • 不能很好地与 13 一起工作,例如...这比看起来要复杂一点! (另外,您需要确保您发布的代码实际返回所选的suffixSelector!)
    • 粘贴函数可以放入while循环吗?因为我不知道为什么当粘贴的东西在while循环中时什么都没有打印出来???
    • 取决于...你能粘贴你的循环,以便我们看到完整的代码吗?
    • 别担心。我是愚蠢的。我认为粘贴功能也包含打印功能。显然,它只连接,但不打印。所以我必须做打印(粘贴(......))。感谢您的帮助
    【解决方案2】:

    使用sprintf

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

    【讨论】:

      【解决方案3】:

      这里有一种稍微不同的方法来将每个整数与它的适当后缀挂钩。如果你把它分开,你会发现它确实捕获了构造每个整数的序数形式的句法(?)规则。

      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 的元素.

      【讨论】:

        猜你喜欢
        • 2018-11-08
        • 2021-05-21
        • 2018-10-03
        • 2021-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-01
        • 1970-01-01
        相关资源
        最近更新 更多