Is there a way to pass vector in for loop

46 Views Asked by At

I am very new to R programming. I am trying to create a small loop where I am passing numbers (1 and 2) to asdf.

for (i in c(4,28)){
  asdf = i
}

Expected output

asdf
4
28

Is there a way to achieve the above result

1

There are 1 best solutions below

3
Flap On

A loop works iteratively, so in your code in the last iteration you overwrite the previous value in the vector asdf and assign it the new value of 28.

If you want to store both values in the vector, you first initialize an empty vector. For each iteration then, append the value of interest to the already existing vector. As detailed in the code below:

asdf <- c() #initialize empty vector

for (i in c(4,28)){
asdf <- c(asdf, i)
}

Output:

> asdf
[1]  4 28