首页 > 解决方案 > 从矩阵创建新列

问题描述

我有一个n x 2矩阵,例如:

x <- matrix(1:4, nrow = 2, ncol = 2)

我必须创建一个新列来存储结果

(a11+a12)-a22, (a21+a22)-a32, ...

等等。a32不存在所以它被认为是0。有没有简单的方法在 R 中做到这一点?

我尝试使用该apply()功能但没有运气。所需的输出是具有值的列

0
6

标签: r

解决方案


像这样的东西?

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

推荐阅读