1

I want to make a vector using a loop.

Here's my R code:

vec_teamCodes <- c()
x <- 0
while (x < 10) {
  append(vec_teamCodes,"Hello")
  x <- x+1
}

But when I run it, vec_teamCodes() remains NULL.

Why? How do I fix my code?

alistaire
  • 42,459
  • 4
  • 77
  • 117
Username
  • 3,463
  • 11
  • 68
  • 111
  • 4
    `append` does not assign value to variables in arguments, it creates a new variable. – Bulat Jun 19 '16 at 21:25
  • 4
    I think you're either looking for `rep('Hello', 10)` or `paste(rep('Hello', 10), collapse = '')` – alistaire Jun 19 '16 at 21:28
  • 9
    In general you will want to avoid extending vectors in this fashion. Though it works alright in this specific context, it is highly inefficient and will bite you in larger problems. Consider reading [@JoshuaUlrich's answer](http://stackoverflow.com/a/22235924/3358272) to a question on appending to a vector. – r2evans Jun 19 '16 at 21:31

1 Answers1

5

Try this:

vec_teamCodes <- c()
x <- 0
while (x < 10) {
  vec_teamCodes <- c(vec_teamCodes,"Hello")
  # OR
  # vec_teamCodes <- append(vec_teamCodes,"Hello")
  x <- x+1
}


[1] "Hello" "Hello" "Hello" "Hello" "Hello" "Hello" "Hello" "Hello" "Hello" "Hello"
989
  • 12,579
  • 5
  • 31
  • 53