R programming - Adding extra column to existing matrix

前端 未结 2 1543
清酒与你
清酒与你 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: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]) )
    

提交回复
热议问题