【问题标题】:why c() does not working in this recursive function in R?为什么 c() 在 R 中的这个递归函数中不起作用?
【发布时间】:2020-04-02 07:31:49
【问题描述】:

enter image description here

我知道存在与我想要制作的功能类似的“独特”功能,但我想制作此功能。 我希望这个函数最终返回包含输入向量的唯一元素的“结果”。 但我不知道为什么这个函数的结果与我的预期完全不同。 为什么要在结果和新的唯一元素之前组合的 c 不起作用。 请告诉我如何修复我的代码。 谢谢。

【问题讨论】:

  • 您好,欢迎来到 SO,您能否将问题中的代码作为文本包含在问题中?您可以通过选择它并单击编辑器菜单栏中的大括号将其标记为代码。
  • 请在此处粘贴您的函数代码,而不是提供图片链接

标签: r function recursion unique


【解决方案1】:

我认为您所期望的可能如下所示,其中result 应该是m_uni 的参数:

m_uni <- function(x,result = c()) {
  if (class(x)=='numeric'| class(x)=='character') {
    if (length(x) <= 1){
      return(result)
    } else {
      if (x[length(x)] %in% result) {
        x <- x[-length(x)]
        m_uni(x,result)
      } else {
        result <- c(result,x[length(x)])
        x <- x[-length(x)]
        m_uni(x,result)
      }
    }
  } else {
    return('This function only gets numeric or character vector')
  }
}

这样

> m_uni(x)
[1]  0  4  5 -2

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 2022-11-12
    • 1970-01-01
    相关资源
    最近更新 更多