【问题标题】:R function - Error argument is missing, with no defaultR 函数 - 缺少错误参数,没有默认值
【发布时间】:2020-01-14 11:57:06
【问题描述】:

我正在测试 R 中的一个简单函数,该函数应该将时间序列对象转换为数据框。 然而,代码在函数外部运行良好,但在函数内部却给了我对象中的错误。

>fx<-function(AMts) {
  x<-as.data.frame(AMts)
  return(x)
}
>fx()

我希望在我的环境中有 data.frame x,但我得到了 Error in as.data.frame(AMts) : argument "AMts" is missing, with no default

【问题讨论】:

  • fx(AMts = AMts)。您必须告诉函数您希望它转换什么。现在AMTs 只是一个函数参数(即使它是您的全局环境中的时间序列的名称)
  • 当您调用函数 fx(x) 时,您是否指定了类似 fx(AMts) 的参数?
  • 在阅读了 datajoel 的解释后,我现在这样做了。它有效。谢谢

标签: r function parameter-passing


【解决方案1】:

如果它在函数内部,则需要使用“

>fx<-function(AMts) {
  x<<-as.data.frame(AMts) # "<<-" is what saves "x" in your environment
  return(x) # remove this line; this prints data frame "x" to the console, but it doesn't save it
}
>fx(AMts)

编辑:正如评论者已经指出的那样,您没有在函数中包含任何参数。上面我将其设为 fx(AMts) 以明确您也需要将 AMts 传递给函数。

【讨论】:

  • 他有两个问题。我可能在 MDEWITT 和 Greg 首先正确指出的编辑之前被否决了。但他希望“x”作为他环境中的数据框,唯一的方法是使用
猜你喜欢
  • 1970-01-01
  • 2019-07-03
  • 2023-01-13
  • 1970-01-01
  • 2014-03-15
  • 2016-06-08
  • 2017-12-09
  • 2020-07-04
相关资源
最近更新 更多