【问题标题】:Unable to store the results of a double for loop无法存储双 for 循环的结果
【发布时间】:2012-07-07 13:54:13
【问题描述】:

我对 R 很陌生,并编写了一个双 for 循环,它完全符合我的要求(具有特定块长度的索引号的块引导)。但是,我无法将 print(x_sample) 显示的内容存储在矩阵中。 我已经尝试了 lapply 以及我可以在这里找到的所有其他内容,但我无法自己解决问题。我真的希望你能提供帮助。 非常感谢提前

Here is my code:
x <- c(1:1060,1,2,3)
x_sample  <- numeric(119*4)
for (i in 1:3){
    for (j in 0:119){
          idx <- sample(1:1060,1,replace=TRUE)
          x_sample[(4*j+1):(4*j+4)] <- x[(idx):(idx+3)] }
    print(x_sample)}

【问题讨论】:

  • 请接受对您最有帮助的答案 :) 答案左侧会有一个复选标记——点击它以接受该答案。

标签: r for-loop store


【解决方案1】:

你的意思是这样的吗?:

values <- c(1:1060, 1, 2, 3)
m <- sapply(sample(1:1060, 360, replace=TRUE), function(idx)values[(idx):(idx+3)])

【讨论】:

    【解决方案2】:

    在循环之前创建一个矩阵,然后填充矩阵:

    x <- c(1:1060,1,2,3)
    mat <- matrix(nrow=480, ncol = 3)
    for (i in 1:3){
      for (j in 0:119){
        idx <- sample(1:1060,1,replace=TRUE)
        mat[(4*j+1):(4*j+4), i] <- x[(idx):(idx+3)] }
      print(mat)}
    

    【讨论】:

    • 谢谢EDi!解决方案比我预期的要容易得多。我想我还需要练习......
    猜你喜欢
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 2016-07-13
    相关资源
    最近更新 更多