R programming - Adding extra column to existing matrix

前端 未结 2 1540
清酒与你
清酒与你 2021-02-02 10:10

I am a beginner to R programming and am trying to add one extra column to a matrix having 50 columns. This new column would be the avg of first 10 values in that row.

相关标签:
2条回答
  • 2021-02-02 10:23

    Methinks you are over thinking this.

    a <- matrix(1:5000, nrow=100)
    a <- transform(a,  first10ave = colMeans(a[1:10,]))
    
    0 讨论(0)
  • 2021-02-02 10:27

    Bam!

    a <- matrix(1:5000, nrow=100)
    a <- cbind(a,apply(a[,1:10],1,mean))
    

    On big datasets it is however faster (and arguably simpler) to use:

    cbind(a, rowMeans(a[,1:10]) )
    
    0 讨论(0)
提交回复
热议问题