r - 按行名组合/匹配/合并向量
问题描述
我有一个变量名向量和几个单行矩阵。
我想创建一个新矩阵。新矩阵是通过将矩阵的行名与单行匹配/合并来创建的。
例子:
变量名向量
Complete_names <- c("D","C","A","B")
几个单行矩阵
Matrix_1 <- matrix(c(1,2,3),3,1)
rownames(Matrix_1) <- c("D","C","B")
Matrix_2 <- matrix(c(4,5,6),3,1)
rownames(Matrix_1) <- c("A","B","C")
期望的输出:
Desired_output <- matrix(c(1,2,NA,3,NA,6,4,5),4,2)
rownames(Desired_output) <- c("D","C","A","B")
[,1] [,2]
D 1 NA
C 2 6
A NA 4
B 3 5
我知道有几个类似的帖子,但这些以前的答案并不适合这个。
解决方案
主要工作可以用 来完成merge
,返回一个数据框:
merge(Matrix_1, Matrix_2, by = "row.names", all = TRUE)
# Row.names V1.x V1.y
# 1 A NA 4
# 2 B 3 5
# 3 C 2 6
# 4 D 1 NA
根据您的目的,您可以进一步修改名称或摆脱Row.names
.
推荐阅读
- ember.js - EMBER JS - 仅在需要时从后端获取关联的模型数据
- python - 迭代时未在熊猫数据框中设置值
- javascript - Node js - Push() 函数在参考和 mongodb 中无法正常工作
- android - 如何从 Android Studio 运行单个 Kotlin 类
- javascript - 如何向 window.addEventListener 添加时间
- ionic-framework - 离子组件在框架中不起作用
- java - 使用 apache poi 循环数组数据
- c++ - 如何检查位枚举中是否存在值?
- javascript - 如何在 D3 饼图中动态放置标签
- visual-c++ - msft c 未解决的外部绑定以在 win32 控制台应用程序中使用 dll 函数