在R中将向量传递给函数

3
我正在尝试创建一个函数,将向量中的每个元素减去2。但是,每当我将向量作为参数传递给该函数时,它都会输出错误信息:

Error in sub(x) : argument "x" is missing, with no default.

因此,我有一个名为x1的向量,我的函数调用看起来像这样:sub(x1)
任何帮助将不胜感激。
sub <- function(x)
{
   for(i in 1:length(x))
   {
      x[i] = x[i]-2
   }
   return(x)
}

4
x1的外观是什么样子。... str(x1)的输出结果。到目前为止,您的示例无法复制。顺便说一句:您的函数正在执行x-2操作。调用sub(1:4)可以正常工作。 - undefined
3
除了jogo的评论之外:尽量不要将您的函数命名为“sub”,因为这个名称已经被使用,参见?sub - undefined
最终你忘记运行函数定义了...! - undefined
2
不需要循环甚至函数,考虑“向量化”。例如,x <- 1:100; x <- x - 2` 可以实现你想要的效果。 - undefined
2个回答

5
在R中,许多函数和运算符(只是函数的一种特殊形式)都是矢量化的。向量化意味着函数/运算符自动适用于矢量(或类似矢量对象)的所有元素。
因此,我们的问题可以用更少的代码来解决。此外,使用向量化函数(尤其是基本的东西,如+-,...)比循环元素要快得多。
# define function that does subtraction
sub <- function(x){
  x - 2
} 

# define vector with numbers ranging from 1 to 20
my_vector <- 1:20 

# call function with my_vector as argument
sub(my_vector)

关于您的错误:

Error in sub(x) : argument "x" is missing, with no default.

这个错误提示您调用了一个函数sub()时没有给它的参数x提供适当的值。由于您没有提供它,也没有默认值,并且在R中找不到其他值,因此它不知道该怎么做并发出(抛出)错误。

我可以重现您的错误,操作如下:

# call sub without argument
sub()
## Error in sub() : argument "x" is missing, with no default

我可以通过为参数x提供一个值来防止它发生,像这样:

# call sub with value for x 
sub(1)
sub(x = 1)

...或者我可以提供默认值,例如:

# define function with default values
sub <- function(x = NULL){
  x - 2
}

# call new 'robust' sub() function without arguments
sub()
## numeric(0)

我可以提供默认值,如下所示:

...或者我可以像这样提供默认值:

# define function with default values
sub <- function(x){
  if ( missing(x) ){
    x <- NULL
  }
  x - 2
}

# call new 'robust' sub() function without arguments
sub()
## numeric(0)

Resources:


1
我猜你忘记运行函数定义了:
sub2 <- function(x)
{
  for(i in 1:length(x))
  {
    x[i] = x[i]-2
  }
  return(x)
}
sub2(1:4) ## works fine

sub(1:4) ## Error calling the function sub(pattern, replacement, x, ...)

在 sub(1:4) 中出现错误:缺少参数“x”,且没有默认值

或者

> x1 <- 1:4
> sub(x1) ## Error
Error in sub(x1) : argument "x" is missing, with no default

如果您为函数选择了另一个名称(不是现有 R 函数的名称),则消息很清晰(要在新的 R 会话中运行):
# sub2 <- function(x)
# {
#   for(i in 1:length(x))
#   {
#     x[i] = x[i]-2
#   }
#   return(x)
# }
sub2(1:4)
# > sub2(1:4)
# Error in sub2(1:4) : could not find function "sub2"

我将函数定义注释掉以模拟未运行函数定义的情况。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接