Math is like Friday
Math is like Friday

Reputation: 21

How can I create a vector by only using for loop? (vector is specified in the body)

(1,2,2,3,3,3,4,4,4,4,...,n,...,n)

I want to make the above vector by for loop, but not using rep function or the other functions. This may not be good question to ask in stackoverflow, but since I am a newbie for R, I dare ask here to be helped.

(You can suppose the length of the vector is 10)

Upvotes: 1

Views: 86

Answers (4)

Bruno Zamengo
Bruno Zamengo

Reputation: 870

I'd like to give you a few hints if using rep would have been possible which may help you with R in general. (Without rep usage, just look at @akrun)

Short answer using rep

rep(1:n, 1:n)

Long Answer using rep

First of all, we should try to have a look at official sources:

From the previous two (and other sources as well) you will find two interesting functions:

  • : operator: it can be used to generate a sequence of integers from a to b like a:b. Typing 1:3, for instance, gives you the 1, 2, 3 vector
  • rep(x, t) is a function which can be used to replicate the item(s) x t times.

You also need to know R is "vector-oriented", that is it applies functions over vectors without you typing explicits loops. For instance, if you call repl(1:3, 2), it's (almost) equivalent to running:

for(i in 1:3)
    rep(i, 2)

By combining the previous two functions and the notion R is "vector-oriented", you get the rep(1:n, 1:n) solution.

Upvotes: 1

Allan Cameron
Allan Cameron

Reputation: 174506

You can do this with a single loop, though it's a while rather than a for

n <- 10
x <- 1; 
i <- 2; 

while(i <= n) 
{
 x <- c(x, 1/i); 
 if(sum(x) %% 1 == 0) i = i + 1; 
}

1/x

Upvotes: 0

Tanner33
Tanner33

Reputation: 140

I am not sure why you don't want to use rep, but here is a method of not using it or any functions similar to rep within the loop.

`for (i in 1:10){
  a<-NA
  a[1:i] <- i
  if (i==1){b<-a}
  else if (i >1){b <- c(b,a)}
  assign("OutputVector",b,envir = .GlobalEnv)
  }`
`OutputVector`

Going for an n of ten seemed subjective so I just did the loop for numbers 1 through 10 and you can take the first 10 numbers in the vector if you want. OutputVector[1:10]

Upvotes: 0

akrun
akrun

Reputation: 887881

With a for loop, it can be done with

n <- 10
out <- c()
for(i in seq_len(n)){
      for(j in seq_len(i)) {                   
         out <- c(out, i)
           }                  

}

In R, otherwise, this can be done as

rep(seq_len(n), seq_len(n))

Upvotes: 5

Related Questions