使用不同长度的序列填充for循环中的数组

时间:2017-05-13 10:02:54

标签: r for-loop indexing

我在一个小问题上遇到了一些困难。我想得到的是一个 dim = 1数组,可以通过这个for循环填充。

最小 - 示例(它不起作用!):

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)
}

我猜有两个问题:

  • Result[n]的长度不一样
  • n中的索引Result[n]错误。实际上,它应该是动态的,因此,随着每个新的n而改变。
你能帮助我吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

我们可以使用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

或使用for循环

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

答案 1 :(得分:1)

使用sequencerep

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

你也可以创建一个超大的&#39;矩阵并选择下三角形:

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
相关问题