【问题标题】:Hi. I am new to R and am really struggling with writing my function with for and while loop. Can someone tell me the for and while loop for the qs?你好。我是 R 的新手,并且在使用 for 和 while 循环编写我的函数方面非常挣扎。有人可以告诉我 qs 的 for 和 while 循环吗?
【发布时间】:2021-12-07 04:24:58
【问题描述】:

编写一个函数h1,它使用for循环和显式公式

h(x, n) = 1 + x + x2 + ...xn = ∑xn

代码:

h2 <- function(x,n){
  i <- 1
  out=0
  for (i  in seq(from=0,to=n)) {
    out = out + x^i
    }
}

我试过了,但这似乎不起作用?有没有另一种方法可以找到这个问题的 for 和 while 循环

【问题讨论】:

    标签: r function


    【解决方案1】:

    函数返回其主体中最后一条语句的结果,在本例中为for,但for 始终返回NULL。 (for 之后的那一行被认为是for 的一部分,所以它不被认为是最后一行。)

    res <- for(i in 1:3) i
    res
    ## NULL
    

    确保out 是最后运行的语句。那就是添加这个

    out
    

    作为正文的最后一行,就在最后的 } 之前。

    请注意,这种单线性也可以:

    sum(x^(0:n))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-22
      • 2019-01-13
      • 1970-01-01
      • 2018-05-24
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 2014-02-01
      相关资源
      最近更新 更多