Your code is doing exactly what you specified. You provided a value of x and a value of y, and that was the result returned:
> 0^0+0
[1] 1
To use for
, you must specify a sequence, 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 an object of appropriate size 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 came to the solution when you edited your question, just didn’t realize it was just that:
suaFuncao <- function(y, x) sum(y^(0:x))
> suaFuncao(2, 3)
[1] 15
sum
, is already a function of R; 1) Start withsum <- 0
; 2) Take the cycle from the inside, there is doing nothing there.– Rui Barradas
Note to comment above: If you want you can start with
sum <- 1
but then the cyclefor
will be for values1:x
and not0:x
.– Rui Barradas