【问题标题】:R For Loop unable to store the dataR For Loop无法存储数据
【发布时间】:2011-12-12 13:26:31
【问题描述】:

这可能是一个非常简单的问题,但我对 R 很陌生。我有一个 for 循环,

holder<-rep(0,3)
for(i in 1:3) {
  apple<-c(i+1, i*2, i^3)
  holder[i]<-apple
}

我收到警告消息:

Warning messages:
1: In holder[i] <- apple :
  number of items to replace is not a multiple of replacement length
2: In holder[i] <- apple :
  number of items to replace is not a multiple of replacement length
3: In holder[i] <- apple :
 number of items to replace is not a multiple of replacement length

所以我尝试将 holder 设置为矩阵,而不是向量。但我无法完成它。任何建议将不胜感激。

最好的,

詹姆斯

【问题讨论】:

    标签: r loops for-loop storage


    【解决方案1】:

    您可以将其作为矩阵使用:

    holder<-matrix(0,nrow=3,ncol=3)
    for(i in 1:3){
        apple<-c(i+1, i*2, i^3)
        holder[,i]<-apple  # columnwise, that's how sapply does it too
    }
    

    或者你使用列表:

    holder <- vector('list',3)
    for(i in 1:3){
        apple<-c(i+1, i*2, i^3)
        holder[[i]]<-apple
    }
    

    或者你只是用 R 的方式来做:

    holder <- sapply(1:3,function(i) c(i+1, i*2,i^3))
    holder.list <- sapply(1:3,function(i) c(i+1, i*2,i^3),simplify=FALSE)
    

    附带说明:如果您在 R 中遇到这个非常基本的问题,我强烈建议您浏览您在网络上找到的任何介绍。您可以在以下位置获得它们的列表:

    Where can I find useful R tutorials with various implementations?

    【讨论】:

    • 我只是在输入这个答案:)
    • 谢谢。我一定会看看这些教程。最佳
    • 您好,只是一个评论。我总是在试图提取 for 循环输出时遇到困难。我已经查看了几本 R 教程和书籍,并且这些示例总是非常基础的。实际上,for 循环背后的逻辑很简单,但是根据重复的函数,事情会变得复杂。因此,输出可能是向量、列表等,而获取它们对我来说是一场噩梦。
    • @Rafael 如果函数的输出在每次循环中都是未知的或不同的,那么使用列表是最安全的。但在大多数情况下,您可以使用 sapply() 或 lapply() 解决所有问题。
    • 您好 Joris,很抱歉我迟到的回答说谢谢。我会记住你的建议
    【解决方案2】:

    您应该制作一个包含正确尺寸的矩阵,然后填充这些值。还记得在 i 之后放置一个逗号,以便正确索引矩阵。

    holder<-matrix(nrow = 3, ncol = 3)
    
    for(i in 1:3)
    
    {
    
      apple<-c(i+1, i*2, i^3)
    
      holder[i,]<-apple
    
    }
    

    【讨论】:

    • @user1021000 实际上你对“持有人”的定义有问题,它应该是矩阵而不是向量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多