R 编程 - 向现有矩阵添加额外的列 [英] R programming - Adding extra column to existing matrix

查看:33
本文介绍了R 编程 - 向现有矩阵添加额外的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 编程的初学者,正在尝试向具有 50 列的矩阵添加一个额外的列.这个新列将是该行中前 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.

randomMatrix <- generateMatrix(1,5000,100,50)
randomMatrix51 <- matrix(nrow=100, ncol=1)

for(ctr in 1:ncol(randomMatrix)){  
randomMatrix51.mat[1,ctr]  <- sum(randomMatrix [ctr, 1:10])/10
}

这给出了以下错误

Error in randomMatrix51.mat[1, ctr] <- sum(randomMatrix[ctr, 1:10])/10 :incorrect
number of subscripts on matrix

我试过了

cbind(randomMatrix,sum(randomMatrix [ctr, 1:10])/10)

但它只适用于一行,如果我在循环中使用这个 cbind,所有旧值都会被覆盖.

But it only works for one row, if I use this cbind in the loop all the old values are over written.

如何在新列中添加前 10 个值的平均值.除了遍历行之外,还有更好的方法吗?

How do I add the average of first 10 values in the new column. Is there a better way to do this other than looping over rows ?

推荐答案

呸!

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]) )

这篇关于R 编程 - 向现有矩阵添加额外的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆