0

I want to create what I think is a loop in R, simplifying code that follows this pattern:

n1<-n + 10
n2<-n1 + 10
n3<-n2 + 10
etc...

However I'm not quite sure how to do this- I know it's not a 'for', 'while', or 'repeat' loop as those are based on true/false outputs whereas here I need the loop to run of outputs from earlier iterations of the loop. Then following on from this is it possible to create this simplified loop with a periodic change? e.g.

n1<-n + 10
n2<-n1 + 10
n3<-n2 + 10 +5
n4<-n3 + 10
n5<-n4 + 10
n6<-n5 + 10 +5
etc...

So every third iteration has an additional input. Feel free to redirect me if this has been asked before. I'm not sure the term 'loop' is right for this but I haven't known what else to search. Any help would be much appreciated!

I K
  • 27
  • 4
  • 2
    Do you want to create several scalars, a vector or a list? Or something else? Modifying the action of the loop every kth iteration is straightforward, so I'm not sure what your question is primarily about the construction of the loop itself or the output(s) from it. – Limey Jun 26 '20 at 11:37
  • So I want to create a vector of N1:N50 and to print N50 in the end. My question is mostly how to construct the loop in the first place so I don't have to write the n1<-n+10 over and over 50 times. Then a second question is if this loop can be created how would you alter every kth iteration – I K Jun 26 '20 at 11:48

3 Answers3

2

using purrr and solution @Limey

library(tidyverse)
map_dbl(1:50, ~ .x + 10 + ifelse(.x %% 3 == 0, 5, 0))
Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14
1

From OP's answer to my comment, I think

n <- 0
for (i in 1:50) n <- n + 10 + ifelse(i %% 3 == 0, 5, 0)
n

Giving n = 580, But @Chris deserves the accepted answer as he answered OP's original question in its literal sense.

or, to get a vector:

n <- c(10)
for (i in 2:50) n[i] <- n[i-1] + 10 + ifelse(i %% 3 == 0, 5, 0)
n
Limey
  • 10,234
  • 2
  • 12
  • 32
0

Possible answer:

n0 <- 1

for (i in 1:6) {
  if (i %% 3 != 0) {
    assign(paste0("n", i), get(paste0("n", i-1)) + 10)
  } else {
    assign(paste0("n", i), get(paste0("n", i-1)) + 10 + 5)
  }
}
Chris
  • 266
  • 1
  • 6