[英]Creating a new column from a matrix
我有一个n x 2矩阵,例如:
x <- matrix(1:4, nrow = 2, ncol = 2)
我必须创建一个新列来存储结果
(a11+a12)-a22, (a21+a22)-a32, ...
等等。 a32
不存在,因此被视为0
。 在R中有一个简单的方法吗?
我试过没有运气使用apply()
函数。 所需的输出是带有值的列
0
6
像这样吗
x <- matrix(1:4, nrow = 2, ncol = 2)
# obtain the row sum of x
rs = rowSums(x)
# obtain the last column from the matrix
x = x[,ncol(x)]
# remove the first value and add a 0 at the end
# since your last value will always be 0
x = x[-1]
x = c(x, 0)
rs - x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.