r - 如何只保留 R 中 4 个数据帧之间的公共(public)行名?

标签 r matrix

我有 4 个基因数据框,每个数据框都有基因名称作为行和大约 20 列样本数据。因此每个矩阵都有一定数量的行(基因):

  • A:10,000 个基因
  • B:15,000 个基因
  • C:35,000 个基因
  • D:12,000 个基因

这是我试过的,它没有选择 9,000 个公共(public)行(基因)的完整列表

Data_A = read.csv("matrix_A.csv");
Data_B = read.csv("matrix_B.csv");
Data_C = read.csv("matrix_C.csv");
Data_D = read.csv("matrix_D.csv");

Expr_A = as.data.frame(t(Data_A[, -c(1:8)]))
Expr_B = as.data.frame(t(Data_B[, -c(1:8)]))
Expr_C = as.data.frame(t(Data_C[, -c(1:8)]))
Expr_D = as.data.frame(t(Data_D[, -c(1:8)]))

commonGenes1 = intersect (rownames(Data_A),rownames(Data_D))
commonGenes2 = intersect (rownames(Data_B),rownames(Data_D))
commonGenes3 = intersect (rownames(Data_C),rownames(Data_D))

Data_A = Data_A[commonGenes1,]
Data_B = Data_B[commonGenes2,]
Data_C = Data_C[commonGenes3,]

它们都有 9,000 个共同基因,尽管数据太大,我无法在 Excel 中执行此操作。我正在使用 R 来处理数据,有没有办法在 R 中的 4 个数据帧之间选择共同基因?

4 个矩阵的示例如下: http://www.filedropper.com/matrixexample

最佳答案

让我们实际将事物放入列表中(如您的标题所示),这是一种很好的做法。

list_of_data = list(Data_A, Data_B, Data_C, Data_D)
## for demo purposes, you can use
# list_of_data = list(mtcars[1:6, ], mtcars[4:9, ])

# this will get the intersection of the row.names for everything in the list
common_names = Reduce(intersect, lapply(list_of_data, row.names))

list_of_data = lapply(list_of_data, function(x) { x[row.names(x) %in% common_names,] })

感谢 @eipi10 提供了一种更好的方法来过滤列表中每个数据框的行。查看修订历史以了解一个蹩脚的 for 循环。

关于r - 如何只保留 R 中 4 个数据帧之间的公共(public)行名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30131251/

相关文章:

r - 求序数中位数的惯用方法

r - 分割向量

r - 在循环中运行箱形图/水平线时,hline 索引没有改变的问题

c - 通过引用和扫描值传递矩阵

R - 混淆矩阵中缺失因子的条件替换

r - 如何根据R中缺失数据的日期列计算数据框中多列的月平均值

regex - R正则表达式 - 在括号之间拆分

algorithm - 给定矩阵 [i, j] 中的一个位置,找到它所属的 block

c - C中生成随机数的函数

python - Numpy 高效大矩阵乘法