cycle for calculating a function

3

I want to cycle for but it is not working. My knowledge of 'R' is still meager. I want to calculate a F(y, x) = 1 + y + y^2 + ... + y^x = sum(y^(0:x)) function.

I wrote the following code, but it is giving a result that is not what I want. What is wrong?

> sum <- 1 
> for(i in 0:3){
+     for(y in 0:3){
+             sum <- sum + y ^ (i)
+     }
+ }
  

print (sum)   [1] 61

    
asked by anonymous 27.10.2018 / 22:19

2 answers

2

Your code is doing exactly what you specified. You provided a value of x and a value of y, and that was the returned result:

> 0^0+0
[1] 1

To use for , you must specify a string, for example:

x <- 3

> for(i in x) print(i+1)
[1] 4

> for(i in 1:x) print(i+1)
[1] 2
[1] 3
[1] 4

To store the values, you must have a dimension object appropriate to receive the result of each turn, or you will only have the last value:

for(i in 0:x) y = x ^ i + x
> y 
[1] 30
# o objeto y teve o valor atualizado a cada volta

y <- rep(NA, x+1)
for(i in 0:x) y[i+1] = x ^ i + x
> y
[1]  4  6 12 30

But R is optimized for vector operations, it is best to avoid loops whenever possible. You already arrived at the solution when you edited your question, just did not realize it was just that:

suaFuncao <- function(y, x) sum(y^(0:x))

> suaFuncao(2, 3)
[1] 15
    
28.10.2018 / 00:42
0

Here is a very simple for loop. And the comparison to the result of the function of #

suaFuncao <- function(y, x) sum(y^(0:x))

suaFuncao2 <- function(y, x){
  s <- 1
  for(k in seq_len(x)) s <- s + y^k
  s
}

suaFuncao(2, 3)
#[1] 15

suaFuncao2(2, 3)
#[1] 15
    
01.11.2018 / 20:02