R 参数个数可变的递归函数

R 参数个数可变的递归函数,r,recursion,R,Recursion,我试图构建一个函数来计算以下公式 f(x) = X1*B1 + X2*B2 ... + Xn * Bn 为了做到这一点,我发现它很有用。。。和递归性 这是我解决问题的方法: resolve_polinom <- function(x, b, ...){ n <- length(list(...)) func_args <- list(...) if (n == 0){ # If there are no more elements on ...

我试图构建一个函数来计算以下公式

f(x) = X1*B1 + X2*B2 ... + Xn * Bn
为了做到这一点,我发现它很有用。。。和递归性

这是我解决问题的方法:

resolve_polinom <- function(x, b, ...){

  n <- length(list(...))
  func_args <- list(...)

  if (n == 0){ 
    # If there are no more elements on ... 
    return(x * b)

  }else{
    # If ... contains elements then 
    return(x * b + resolve_polinom(x= ..1, b= ..2, list(...)[-c(1,2)]))
  }
}

# list(...)[-c(1,2)] 

在R中创建递归函数通常是一个坏主意(如果不能保证不会超过最大值)

如果您坚持调用函数的方式,我建议:

resolve_polinom <- function(...) {
  values <- c(...)
  m <- matrix(values, ncol = 2, byrow = TRUE)
  sum(m[,1] * m[, 2])
}

如果在data.table中有两个对应的列,则后者应该很容易工作。

在R中创建递归函数通常是个坏主意(如果不能保证不会超过该值)

如果您坚持调用函数的方式,我建议:

resolve_polinom <- function(...) {
  values <- c(...)
  m <- matrix(values, ncol = 2, byrow = TRUE)
  sum(m[,1] * m[, 2])
}

如果您在data.table中有两个对应的列,则后者应该很容易工作。

听起来您试图做的是矩阵乘法。其中x是具有一定数量的行/观测值和n列的矩阵,b是具有系数的长度为n的向量

以下是一个例子:

set.seed(314)

x <- matrix(c(rep(1,10),sample(1:10,30, replace = T)), ncol = 4)

b <- 1:4

# multiply the elements of the first observation in x with the elements of b, and then take the sum.
sum(x[1,] * b)

# with matrix multiplication you can do this for all observations at once:
x %*% b
set.seed(314)

听起来你想做的是矩阵乘法。其中x是具有一定数量的行/观测值和n列的矩阵,b是具有系数的长度为n的向量

以下是一个例子:

set.seed(314)

x <- matrix(c(rep(1,10),sample(1:10,30, replace = T)), ncol = 4)

b <- 1:4

# multiply the elements of the first observation in x with the elements of b, and then take the sum.
sum(x[1,] * b)

# with matrix multiplication you can do this for all observations at once:
x %*% b
set.seed(314)

请分享您的数据样本。从data.table开始,它们似乎是做同样事情的一种不太复杂的方式。请参阅以及如何创建请共享您的数据示例。从data.table开始,它们似乎是做同样事情的一种不太复杂的方式。看,以及如何创建一个,啊,我认为你确定了他们真正想要做的。啊,我认为你确定了他们真正想要做的。