Home > database >  R Programming: Run a forloop where I takes on specific values
R Programming: Run a forloop where I takes on specific values

Time:02-16

I am attempting to create a loop that runs a function with specific values of i in a vector:

For example I would like to save i 2 for when i is 1 and 5

test<- c()
for(i in c(1,5)){
  
  test[i] <- i   2
  
}

This ends up printing NA for 2 ,3 and 4: [1] 3 NA NA NA 7

while the result I would like is: [1] 3 7

This is probably very elementary but I cannot seem to figure this out.

CodePudding user response:

R is vectorized, means you can do this:

c(1, 5)   2
# [1] 3 7

for loops in R are often very slow, which is why they are implemented in C in functions of the *apply family, e.g.

sapply(c(1, 5), \(i) i   2)
# [1] 3 7

If you really need to rely on a for loop, If you really need to rely on a "for" loop, you may want to loop over the indices rather than the values (a quite common mistake!):

v <- c(1, 5)
test <- vector('numeric', length(v))
for (i in seq_along(v)) {
  test[i] <- v[i]   2
}
test
# [1] 3 7

CodePudding user response:

Use append

test<- c()
for(i in c(1,5)){
  test<-append(test,i 2)
}
  •  Tags:  
  • r
  • Related