【问题标题】:R: Providing parameters to a function?R:为函数提供参数?
【发布时间】:2018-05-15 07:59:24
【问题描述】:

我有一个名为 plot() 的函数。我希望我的函数采用这样的方式,如果用户只输入plot(),它将绘制函数内部读取的数据中的所有行(将读取plot()内部的数据)

我还希望用户能够从数据中选择他想要绘制的行。因此,如果用户输入 plot(1) ,函数将绘制第一行。如果用户输入plot(1,3),它将绘制第一行和第三行。

我试过这样做,但我不确定如何。

这是我尝试做的:

plot <- function(x){
if(x==0)
{ //reads the whole file and plots all the rows
}
else
{
//reads the specified rows and plots them
}
}

这仅适用于用户想要绘制一行的情况,如 plot(1) 的情况,但如果用户想要多行(即 plot(1,2,3) )则不起作用。

帮助?

【问题讨论】:

  • 无论你做什么,都不要调用函数plotplot 在 R 中是一个相当重要的函数,你不想屏蔽它。
  • 除了 Roland 的评论之外,您的函数的问题在于您使用的是 noch 矢量化的if,即它只处理长度为 1 的输入矢量。

标签: r function plot


【解决方案1】:
test <- function(...){
  rows <- c(...)
  if(!is.null(rows) & !is.integer(rows)){stop("Input is not an integer"!)}
  if(max(rows) > nrow(data)){stop("Out of bounds!")}
  if(is.null(rows)){
    plot(data)
  }else{
    plot(data[rows,])
  }
}

... 可让您输入任何您想要的内容,因此这需要一些错误预防措施。

该函数只是创建一个输入向量,检查长度以查看是否给出了输入,然后绘制整个数据集(未给出输入)或由向量 rows 确定的线。

编辑:将第一个错误预防从 numeric 更改为 integer

从长远来看,您可能需要对这种输入进行更多的错误预防,但现在应该可以了。

【讨论】:

  • 我写的是同样的答案,但会建议if (is.null(rows))
猜你喜欢
  • 2012-02-03
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 2016-10-23
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多