r - 从矩阵创建新列
问题描述
我有一个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
推荐阅读
- python - 如何使用混淆矩阵计算自定义训练的 spacy ner 模型的整体准确性?
- sql-server - SQL 使用 With 子句连接查询
- elasticsearch - Elasticsearch 分析器不会替换撇号 (')
- c# - 如何使列表项的一部分可选择和其他不可选择的wpf
- android - 有没有办法让某些产品口味没有 google-services.json?
- ag-grid - 隐藏列时,ag-grid 无法移动组列
- jboss - 删除欢迎内容处理程序后,我在 jboss eap 7.1 中收到 404 not found 错误
- ios - 集合视图 (UPCarouselFlowLayout) 中的按钮未收到 onclick 事件
- java - TabView:左侧有一些选项卡,右侧有一些选项卡(中间有空格)
- amazon-ecs - AWS ECS 任务无法访问出站