Choc_waffles
Choc_waffles

Reputation: 537

How do i increment by the fraction required and return as vector

Did a for loop and want to return the results as a vector. i seem to only succeed with print. but that's not what i am after

n<-20
for (i in 1:n) {
  start_point <- 0.50
  frac <- (start_point / n) * (i-1+1)
  increment <- start_point + frac
  print(increment)
}

Upvotes: 1

Views: 120

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388972

You are overwriting the increment value in every iteration, you need declare it as a numeric vector and store the value in each iteration using an index.

Some improvements in your current code -

1) no need to initialise start_point in every iteration and it can be outside loop

2) (i - 1 + 1) is just i

n <- 20
increment <- numeric(length = n)
start_point <- 0.50

for (i in 1:n) { 
   frac <- (start_point / n) * i
   increment[i] <- start_point + frac
}

increment
# [1] 0.525 0.550 0.575 0.600 0.625 0.650 0.675 0.700 0.725 0.750 0.775
#     0.800 0.825 0.850 0.875 0.900 0.925 0.950 0.975 1.000

However, you could avoid the loop by using seq

seq(start_point + (start_point/n), by = start_point/n, length.out = n)

#[1] 0.525 0.550 0.575 0.600 0.625 0.650 0.675 0.700 0.725 0.750 0.775
#    0.800 0.825 0.850 0.875 0.900 0.925 0.950 0.975 1.000

Upvotes: 1

Related Questions