2

I've got some struggle with a small issue. What I want to get is a dim=1 array to be filled up with help of this for-loop.

Minimal-Example (it's not working!):

Numbers <- seq(1,5)
Result  <- array(NA)

for(n in Numbers){
  Result[n] <- seq(n,5)  
  # The Result array should be like this:           
  # (1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5)
}

I guess there a two problems:

  • The Result[n] don't have the same length
  • The index n in Result[n] is wrong. Actually, it should be dynamic, thus, change with every new n.

Can you guys help me? Thank you!

Henrik
  • 65,555
  • 14
  • 143
  • 159
Frosi
  • 177
  • 5
  • 12

2 Answers2

1

We can do this with sapply

unlist(sapply(Numbers, function(x) seq(x, 5)))
#[1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5

Or using the for loop

Result <- c()
for(n in Numbers){
 Result <- c(Result, seq(n, 5))
 }
Result
#[1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Using sequence and rep:

n <- 5
sequence(n:1) + rep(0:(n-1), n:1)
# [1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5

You may also create an 'oversized' matrix and select the lower triangle:

m <- matrix(c(NA, 1:n), nrow = n + 1, ncol = n + 1)
m[lower.tri(m)]
# [1] 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5
Henrik
  • 65,555
  • 14
  • 143
  • 159