【问题标题】:printing objects from a double for loop in R从 R 中的双 for 循环打印对象
【发布时间】:2011-10-13 02:59:49
【问题描述】:

我在这里有嵌套 for 循环的代码。我想接收的输出是嵌套循环产生的矩阵列的均值矩阵。因此,内部循环应该运行 1000 次随机向量模拟,并且每次运行一个函数。这本身就可以正常工作,并将输出吐到 R 中。但我想将嵌套循环的输出保存到一个对象(1000 行和 11 列的矩阵),然后只打印该矩阵的 colMeans,到由外循环执行。

我认为问题在于我将内部循环的结果分配给 obj 矩阵的步骤。我已经尝试了 obj[i,]、obj[i]、obj[[i]] 等的所有变体,但没有成功。 R 告诉我它是一个只有一维的对象。

x=ACexp

obj=matrix(nrow=1000,ncol=11,byrow=T)          #create an empty matrix to dump results into
for(i in 1:ncol(x)){                           #nested for loops    
  a=rep(1,times=i)                             #repeat 1 for 1:# columns in x    
  b=rep(0,times=(ncol(x)-length(a)))           #have the rest of the vector be 0    
  Inv=append(a,b)                              #append these two for the Inv vector    
  for (i in 1:1000){                         #run this vector through the simulations    
      Inv2=sample(Inv,replace=FALSE)           #randomize interactions    
      temp2=rbind(x,Inv2)    
      obj[i]<-property(temp2)                   #print results to obj matrix     
  }    
print.table(colMeans(obj))                   #get colMeans and print to excel file    
}

有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: r loops printing for-loop


    【解决方案1】:

    当整个矩阵被修改时,您反复将整个矩阵打印到屏幕上,但您的评论说“打印到 excel 文件”。我猜您实际上想将数据保存到文件中。一起删除 print.table 命令,并在循环完成后使用 write.table()

    write.table(colMeans(obj), 'myNewMatrixFile.csv', quote = FALSE, sep = ',', row.names = FALSE)
    

    (我的首选选项...查看 ?write.table 以选择您喜欢的选项)

    【讨论】:

      【解决方案2】:

      由于您的代码不可重现,我们无法完全确定您想要什么。但是,我猜想该属性会返回一个数字,您希望将其放在obj 矩阵的正确行/列位置,您将其称为obj[row,col]。但是你会遇到麻烦,因为你的两个循环都使用相同的索引i。也许这样的东西对你有用。

      obj <- matrix(nrow=1000,ncol=11,byrow=T)       #create an empty matrix to dump results into
      for(i in 1:ncol(x)){                           #nested for loops    
        Inv <- rep(c(1,0), times=c(i, ncol(x)-i))    #repeat 1 for 1:# columns in x, then 0's   
        for (j in 1:nrow(obj)){                      #run this vector through the simulations    
            Inv2 <- sample(Inv,replace=FALSE)        #randomize interactions    
            temp2 <- rbind(x,Inv2)    
            obj[j,i] <- property(temp2)              #save results in obj matrix     
        }    
      }
      write.csv(colMeans(obj), 'myFile.csv')         #get colMeans and print to csv file   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-06
        • 1970-01-01
        • 2011-06-10
        相关资源
        最近更新 更多