Saa17
Saa17

Reputation: 265

For loop in r using summation

I have this,

sum(x^i) 

with i being greater than or equal to 1.

How can I create a for loop in R for this summation? In other words, how do I format this summation in R?

Upvotes: 0

Views: 201

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389335

If both x and i are vectors you may use for loop as -

x <- 1:10
i <- 1:10
result <- 0

for(e in i) {
  result <- result + sum(x^e)
}
result

If any of x or i goes to infinity, then the result would always be infinity.

Upvotes: 2

Kra.P
Kra.P

Reputation: 15153

For a fixed x and infinite n,

x <- 0.1 # You may change x
s <- 0
n <- 0
while(n < 100) { #If you want inf, let n >=0 then R will freeze recommend large number...
  s <- s + x^(n)
  n<-n+1
}
s

Upvotes: 1

Related Questions